<?php
/*
 UTILS.PHP by martin $ 2010/06/01 07:39:43
*/
define('PPBLOG_ENGINE_VERSION', '1.8.9');
define('V_URL', '(?<!["\'=])(https?|ftp)(://[;\/\?:@&=\+\$,\w\-\.!~%#\|]+)');
define('PATH', strpos(PHP_OS, 'WIN')!==0 ?
 str_replace('//', '', dirname(__FILE__).'/') : str_replace(array('\/','//'), '', str_replace('\\', '/', dirname(__FILE__).'/')) );
define('ROOT_PATH', 'http:'.(isset($_SERVER['HTTPS']) ? 's' : '').'//'.str_replace(array('//','\/'), '/', $_SERVER['HTTP_HOST'].dirname($SS=$_SERVER['SCRIPT_NAME']).'/'));
define('QUERY', htmlspecialchars($_SERVER['QUERY_STRING'], ENT_QUOTES));

define('SHOW_REVIEW_COUNT', 1); // 管理向け者に記事の参照数を表示させるか(記事タイトル右)

if(!defined('WITH_DATE')) define('WITH_DATE', TRUE);

if(!empty($_VARS)){
 if(strpos($SS, 'index.php') || strpos($SS, 'ajax.php')){
  if($mode != 'search' && $mode != 'comment'){
   $_VARS[] = QUERY;
   foreach ($_VARS as $q=>$v){
    if($mode == 'theme' && empty($_GET)) continue;
    if(preg_match("{(?:%3C|%3E|%22|%27|%7C|[\|'\"<>])}i", $q.$v)){
     header("HTTP/1.1 400 Bad Request"); exit('ppBlog::Bad Request!');
    }
   }
  }
  if(isset($_VARS['v']) && $_VARS['v'] == '') exit('ppBlog internal engine is ver.'.PPBLOG_ENGINE_VERSION.'.');
 }
}

include_once('owner/smiley.ini.php'); # get::$_SMILIES

$_FILTER = array(
  '|'=>'&#124;',
  "`"=>'&#96;',
  "$"=>'&#36;',
  ","=>'&#44;',
  '\\'=>'&yen;',
);

$_FILTER1 = $_FILTER + array( # ppBlogでフィルターする入力値1
  "\0"=>'',
  "\t"=>'',
  "\x00"=>'',
);

$_FILTER2 = array( # ppBlogでフィルターする入力値2
  "&"=>'&amp;',
  "<"=>'&lt;',
  ">"=>'&gt;',
  '"'=>'&quot;',
  "'"=>'&#039;',
);

if(isset($_COOKIE['PPBLOG_UCONF']) && strstr($ucnf = $_COOKIE['PPBLOG_UCONF'], ',')){
 $ucnf = explode(',', $ucnf);
 $cc_name = $ucnf[0]; $cc_url = $ucnf[1]; $cc_col = $ucnf[2]; $theme = $ucnf[3];
 $displayMode = strstr(' list box ', ' '.$ucnf[4].' ') ? $ucnf[4] : 'box'; $_asort = isset($ucnf[5]) ? $ucnf[5] : 'descend';
 $displayNumber = isset($ucnf[6]) ? $ucnf[6] : ENTRY_BOX;
} else {
 $cc_name = ''; $cc_url = ''; $cc_col = '333'; $theme = ''; $displayMode = 'box'; $_asort = 'descend'; $displayNumber = ENTRY_BOX;
}

if(empty($theme) || !is_file(PATH.$theme) || USE_THEME_CHANGER==FALSE){
 include_once(PATH.'owner/theme.ini.php'); // $THEME_LIST の読み込み
 $theme = array_values($THEME_LIST); $theme = $theme[0];
}
if(g_('theme') != '' && is_dir(dirname($theme))){
 $theme = g_('theme');
 setcookie('PPBLOG_UCONF', $cc_name.",$cc_url,$cc_col,$theme,$displayMode,$_asort,$displayNumber", time()+30*24*3600);
}

if(g_('view') != ''){
 $displayMode = g_('view');
 setcookie('PPBLOG_UCONF', $cc_name.",$cc_url,$cc_col,$theme,$displayMode,$_asort,$displayNumber", time()+30*24*3600);
}

$theme_dir = dirname($theme).'/';

if(p_('_asort') != ''){
 $_asort = p_('_asort');
 setcookie('PPBLOG_UCONF', $cc_name.",$cc_url,$cc_col,$theme,$displayMode,$_asort,$displayNumber", time()+30*24*3600);
}

if(p_('displayNumber') != ''){
 $displayNumber = p_('displayNumber');
 $displayNumber = is_numeric($displayNumber) ? $displayNumber : ENTRY_BOX;
 $displayNumber = ($displayNumber > 30) ? 30 : $displayNumber;
 setcookie('PPBLOG_UCONF', $cc_name.",$cc_url,$cc_col,$theme,$displayMode,$_asort,$displayNumber", time()+30*24*3600);
}
$ip = isset($ip) ? $ip : (($ip=$_SERVER['REMOTE_ADDR']) ? $ip : '');

if(test_ip($ip)==404){ // アクセス拒否IPチェック
 header("HTTP/1.0 404 Not Found");
 exit;
}

if($mode == '' && is_file($ontime_ini = OD.'ontime.ini.php')){ // オンタイム投稿
 include($ontime_ini);
 if(!empty($ONTIME_LIST)){
  $_timestamp = time();
  $queue = $_queue = array();
  foreach ($ONTIME_LIST as $qid){
   if($_timestamp > $qid) $queue[] = $qid;
  }
  if(!empty($queue)){
   include_once 'utils_admin.php';
   include_once 'cache.php';
   foreach ($queue as $pid){
    list($pid, $send_ping) = explode('|', $pid);
    $log = log_($pid);
    if($log != ''){
     $hit = preg_grep("{^$pid}", file($log));
     if(!empty($hit)){
      $index = array_keys($hit); $index = $index[0];
      list(, $category, $title, $com, $author, $allowComment, $allowPing, $excerpt, $extended) = explode('|', $hit[$index]);
      catch_data(FALSE, $author, $title, $com, $extended, $pid, $category, $allowComment, $allowPing, $index);
     }
    } else $_queue[] = $pid;
   }
   if(!empty($_queue)) rewrite_ini($ontime_ini, $_queue); else {if(is_file($ontime_ini)) unlink(PATH.$ontime_ini);}
   if(isset($hit) && !empty($hit) && $send_ping){
    include_once ('xmlrpc.php');
    send_ping_xmlrpc(BLOG_NAME, ROOT_PATH.'index.php');
   }
  }
 } else unlink(PATH.$ontime_ini);
}

$DIVISION = array('header'=>'', 'title'=>'', 'style'=>'', 'script'=>'', 'body'=>'', 'login'=>'', 'logout'=>'', 'control'=>'');

if($mode == '' && defined('ENABLE_AUTO_MOBCHK') && ENABLE_AUTO_MOBCHK && strstr($SS, 'index.php')){ # 自動モブログ
 include(PATH.OD.'mob.ini.php');
 if($MOB_CFG[1] != '' && (time()-$MOB_CFG[8] > $MOB_CFG[6] * 60)){
  include_once(PATH.'mob.php');
 }
}

if(GET_CLIENT_ENV){
 $DIVISION['header'] .= '
 <div class="hidden">
  <script type="text/javascript" src="'.ROOT_PATH.'stat/get_env.js"></script>
  <noscript><p><img src="'.ROOT_PATH.'stat/get_env.php?q=0" width="1" height="1" alt="" /></p></noscript>
 </div>
 ';
}

if($theme != '') include_once ($theme_dir.'template.php');

$LOGS = my_glob(EXT, 'log/', TRUE, "log.db"); # ログの配列は使い回す

$UID = v_('UID'); $aim = g_('aim', 0);
$page = g_('page')=='' ? 1 : g_('page');
$mode = v_('mode'); $path = g_('path');


if(MODE_STATIC){ # 静的モード
 if(!WITH_DATE && !is_file(OD.'idtitle') && !strpos(getcwd(), 'stat')){
  $LINES = array();
  for($j = 0, $l = count($LOGS); $j < $l; $j++){
   if($fp = @fopen($LOGS[$j], "rb")){
    while(!feof($fp)){
     $line = fgets($fp);
     if($line && substr($line, -2) != '|'.NL) $line .= fgets($fp);
     if($line=='') continue;
     list($uid,,$title,) = explode('|', $line, 4);
     if(strpos($title, ',')){
      list(,$title) = explode(',', $title);
      $LINES[] = "$uid\t$title\n";
     }
    } # while-loop
    fclose($fp);
   } # $fp
  } # for-loop
  rewrite_ini(OD.'idtitle', $LINES, '$IDTITLE');
  unset($LINES);
 }
 if($path != ''){
  if(preg_match('{(list|box)$}', $path, $m)){
   $displayMode = $m[1]; $path = preg_replace('{(list|box)$}', '', $path);
   setcookie('PPBLOG_UCONF', $cc_name.",$cc_url,$cc_col,$theme,$displayMode,$_asort,$displayNumber", time()+30*24*3600);
  }
  if(($pos = strpos($path, 'page/')) !== FALSE){
   $page = substr($path, $pos + 5);
   if(strpos($page, '/')) $page = substr($page, 0, -1);
   list($path,) = explode('page/', $path, 2);
  }
  if(preg_match('|^\d{9,10}d?(?:'.EXT_STATIC.')?$|', $path)){
   $UID = EXT_STATIC=='' ? $path : str_replace(EXT_STATIC, '', $path);
  } elseif(preg_match('|^(\d{6})\-([a-zA-Z0-9\-_]+?)(?:'.EXT_STATIC.')?$|', $path, $mt)){
   if(is_file(PATH.LOG.$mt[1].EXT)){
    $log = file(PATH.LOG.$mt[1].EXT);
    $hit = preg_grep('{,'.$mt[2].'\|}', $log);
    if(!empty($hit)){
     list($UID,) = explode('|', reset($hit), 2);
    }
   }
  } elseif(preg_match('|^([a-zA-Z0-9_,;:%-]+?)(?:'.EXT_STATIC.')?$|', $path, $mt)){
   include_once OD.'idtitle';
   $hit = preg_grep("{(\d{9,10})\t$mt[1]}", $IDTITLE);
   if(!empty($hit)){
    list($UID,) = explode("\t", reset($hit), 2);
   } else {
   }
  } else {
   if(strpos($path, 'category/') !== FALSE){
    $mode = 'category'; $aim = substr($path, 9, -1);
   } else if(strpos($path, 'pages/') !== FALSE){
    $mode = 'pages'; $aim = str_replace(array('pages/', '.txt', '/'), '', $path);
   } elseif(strpos($path, 'archives/') !== FALSE){
    $mode = 'archives'; $aim = substr($path, 9, -1);
   } elseif(strpos($path, 'search/') !== FALSE){
    $mode = 'search'; $sess = substr($path, 7, -1);
   } elseif(strpos($path, 'tags/') !== FALSE){
    $mode = 'tags'; $aim = substr($path, 5, -1);
   } elseif(strpos($path, 'gallery/') !== FALSE){
    $mode = 'gallery'; $aim = substr($path, 8, -1);
   } elseif(preg_match('|(\d{4})/(\d{2})/$|', $path, $m)){
    $date = $m[1].$m[2]; $D = getdate(strtotime($date.'01'));
   } elseif(preg_match('|(\d{4})/(\d{2})/(\d{2})/$|', $path, $m)){
    $date = $m[1].$m[2].$m[3]; $D = getdate(strtotime($date)); $mode = 'show';
   }
  }
 }
}

                            /*******************************************
                                         ユーティリティー関数群
                            *******************************************/
function sanitize_data($input, $filter=3){ // 入出力データの整形
 global $_FILTER1, $_FILTER2;
 if(is_array($input)){
  $_input = array();
  foreach ($input as $key=>$in) $_input[$key] = sanitize_data($in, $filter);
  $input = $_input;
 } else {
  $input = MAGIC_QUOTES ? stripslashes($input) : $input;
  switch ($filter){
   case 3 : $input = mb_str_replace(array_keys($_FILTER2+$_FILTER1), array_values($_FILTER2+$_FILTER1), trim($input)); break;
   case 1 : $input = mb_str_replace(array_keys($_FILTER1), array_values($_FILTER1), trim($input)); break;
   case 2 : $input = mb_str_replace(array_keys($_FILTER2), array_values($_FILTER2), trim($input)); break;
   case 0 : $input = trim($input); break;
  }
 }
 return str_replace(array("\r\n","\r","\n"), '`', $input); # 順序大事
}

function mb_str_replace($search, $replace, $target){
 if(is_array($search)){
  if(!is_array($replace)) $replace = array($replace);
  foreach ($search as $i => $needle){
   $rep = isset($replace[$i]) ? $replace[$i] : $replace[0];
   $target = my_str_replace($needle, $rep, $target);
  }
  return $target;
 } else return my_str_replace($search, $replace, $target);
}

function my_str_replace($search, $replace, $target, $encoding = ENCODE){
 $notArray = !is_array($target) ? TRUE : FALSE;
 $target = $notArray ? array($target) : $target;
 $search_len = mb_strlen($search, $encoding);
 $replace_len = mb_strlen($replace, $encoding);
 foreach ($target as $i => $tar){
  $offset = mb_strpos($tar, $search);
  while ($offset !== FALSE){
   $tar = mb_substr($tar, 0, $offset).$replace.mb_substr($tar, $offset + $search_len);
   $offset = mb_strpos($tar, $search, $offset + $replace_len);
  }
  $target[$i] = $tar;
 }
 return $notArray ? $target[0] : $target;
}

function g_($query, $filter=3){
 if(!isset($_GET[$query])) return '';
 $_query = $_GET[$query];
 if(!is_array($_query) && mb_detect_encoding($_query, ENCODE.', SJIS, sjis-win, ASCII') == 'SJIS'){
  $_query = my_convert_encoding($_query, ENCODE, 'SJIS');
 }
 return sanitize_data($_query, $filter);
}

function p_($query, $filter=3){
 if(!isset($_POST[$query])) return '';
 $_query = $_POST[$query];
 if(!is_array($_query) && mb_detect_encoding($_query, ENCODE.', SJIS, sjis-win, ASCII') == 'SJIS'){
  $_query = my_convert_encoding($_query, ENCODE, 'SJIS');
 }
 return sanitize_data($_query, $filter);
}

function v_($query, $filter=3){
 global $_VARS;
 if(!isset($_VARS[$query])) return '';
 $_query = $_VARS[$query];
 if(!is_array($_query) && mb_detect_encoding($_query, ENCODE.', SJIS, sjis-win, ASCII') == 'SJIS'){
  $_query = my_convert_encoding($_query, ENCODE, 'SJIS');
 }
 return sanitize_data($_query, $filter);
}

function isLoggedIn($name=''){ global $SESSION; return (ADMIN && $name==$SESSION->owner()) ? 1 : 0;}
function isUserLoggedIn(){ global $SESSION; return isset($SESSION->data['ppBlog_UAdmin']) ? 1 : 0;}
function isOwnerLoggedIn(){ global $SESSION; return isset($SESSION->data['ppBlog_OAdmin']) ? 1 : 0;}
function isOwner($name=''){ return ($name==ONAME) ? 1 : 0;}
function isRegisteredUser($name=''){
 global $USR_LIST;
 if((defined('ADMIN') && !ADMIN) || !defined('ADMIN')) return FALSE;
 if(!is_array($USR_LIST)) include_once(OD.'usrlist.ini.php');
 foreach ($USR_LIST as $U){
  if(strpos($U, "|$name|")) return $name;
 }
 return FALSE;
}

function echoHTML($js = array('photoeffect.js', 'oParts.js', 'lib.js')){
 global $DIVISION,$D,$_FILTER1,$theme,$theme_dir,$hd,$ua,$mode,$pp_counter_image,$pp_counter_text,
 $blogbar,$_CALENDAR_TYPE, $_CALENDAR_LANG, $_CALENDAR_START, $_TEMPLATE_HTML, $theme_caption, $_EXTRA_DIVISIONS;

 if($mode=='theme'){
  checkADMIN(TRUE);
  error_reporting(0);
  $theme = p_('aim');
  $_tmp = my_glob('tmp', dirname($theme).'/');
  $scroll = p_('scroll');
  if(is_array($_tmp)){ foreach ($_tmp as $t) unlink($t); }
  $cover = '
   <div style="position: fixed;left:0;top:0;width:100%;height:100%;padding-top:15%;font:600 50pt Arial;text-align:center;color:crimson;z-index:9999;" title="こんな感じの仕上がりです">PREVIEW MODE
    <p><a href="admin.php?mode=theme&amp;aim='.p_('aim').'&amp;sub='.p_('sub').':back&amp;scroll='.p_('scroll').'">[戻る]</a></p>
   </div>
  '.NL;
  switch (p_('sub')){
   case 'html' :
    $html = str_replace('`', NL, p_('editarea', 0));
    rewrite(dirname($theme).'/tmp'.time(), $html);
    if(preg_match('{(<!DOCTYPE .*)TEMPLATE;}s', $html, $html)) $html = $html[1];
    $theme_css = '<link rel="stylesheet" id="ppBlogCSS" href="'.ROOT_PATH.$theme.'" type="text/css" />';
    $html = str_replace('</body>', $cover.'</body>', $html);
    break;
   case 'css' :
    $css = str_replace('`', NL, p_('editarea', 0));
    rewrite($tmp=dirname($theme).'/tmp'.time().'.css', $css);
    $theme_css = '<link rel="stylesheet" id="ppBlogCSS" href="'.ROOT_PATH.$tmp.'" type="text/css" />'.NL;
    include_once(dirname($theme).'/template.php');
    header("Content-type: text/html; charset=utf-8");
    $html = str_replace('</body>', $cover.'</body>', $_TEMPLATE_HTML);
    break;
  }
 } else {
  $html = $_TEMPLATE_HTML;
  $theme_css = '<link rel="stylesheet" id="ppBlogCSS" href="'.ROOT_PATH.$theme.'" type="text/css" />';
 }
 if(!strpos($ua, 'MSIE 6') && !strpos($html, '!DOCTYPE html>')) echo '<?xml version="1.0" encoding="'.ENCODE.'"?>'.NL;
 if(ADMIN){
  if($mode=='edit'||$mode=='write'||$mode=='pages'){
   $DIVISION['script'] = '<script type="text/javascript" src="'.ROOT_PATH.'js/editor.js" charset="'.strtolower(ENCODE).'"></script>';
   $DIVISION['style'] .= '<link rel="stylesheet" href="'.ROOT_PATH.'css/editor.css" type="text/css" media="screen" />';
  }
 }
 $rss2 = (RSS2) ? '<link rel="alternate" type="application/rss+xml" title="RSS2.0" href="'.ROOT_PATH.'feeds/rss2.0.xml" />' : '';
 $atom10 = (ATOM10) ? '<link rel="alternate" type="application/atom+xml" title="Atom feed" href="'.ROOT_PATH.'feeds/atom1.0.xml" />' : '';
 $atom10 .= NL.' <link rel="alternate" href="'.ROOT_PATH.'feeds/gallery.rss" type="application/rss+xml" title="" id="gallery" />';
 $use_calendar_cache = TRUE;
 $Ym = date('Ym',$D[0]);
 //clearstatcache();
 switch ($_CALENDAR_TYPE){
  case 1:
   if($use_calendar_cache && is_file($c=DB.$Ym.'_box1.db') && ((int)date('d') - (int)date('d', filemtime(DB.$Ym.'_box1.db')) === 0)){
    $calendar = get_file_content($c);
   } else $calendar = TableCalendar($D['mon'],$D['year'], 'box', $_CALENDAR_START, 0, $_CALENDAR_LANG, 1); // テーブルボックス型
  break;
  case 2:
   if(is_file($c=DB.$Ym.'_box2.db') && (time()-filemtime($c)) < 43200){
    $calendar = get_file_content($c);
   } else $calendar = TableCalendar($D['mon'],$D['year'], 'box', $_CALENDAR_START, 1, $_CALENDAR_LANG, 1); // テーブルボックス型 + セレクター
  break;
  case 3:
   if(is_file($c=DB.$Ym.'_line1.db') && (time()-filemtime($c)) < 43200){
    $calendar = get_file_content($c);
   } else $calendar = TableCalendar($D['mon'],$D['year'], 'line', 0, 0, $_CALENDAR_LANG, 1); // テーブルライン型
  break;
  case 4:
   if(is_file($c=DB.$Ym.'_line2.db') && (time()-filemtime($c)) < 43200){
    $calendar = get_file_content($c);
   } else $calendar = TableCalendar($D['mon'],$D['year'], 'line', 0, 1, $_CALENDAR_LANG, 1); // テーブルライン型 + セレクター
  break;
  case 5:                                                                                  // リスト要素 仕様
   if(is_file($c=DB.$Ym.'_OL1.db') && (time()-filemtime($c)) < 43200){
    $calendar = get_file_content($c);
   } else $calendar = ListCalendar($D['mon'],$D['year'], $_CALENDAR_START, FALSE, $_CALENDAR_LANG, TRUE);
  break;
  case 6:                                                                                    // リスト要素 + セレクター
   if(is_file($c=DB.$Ym.'_OL2.db') && (time()-filemtime($c)) < 43200){
    $calendar = get_file_content($c);
   } else $calendar = ListCalendar($D['mon'],$D['year'], $_CALENDAR_START, TRUE, $_CALENDAR_LANG, TRUE);
  break;
  default: $calendar = '';
 } #switch
 $DIVISION['style'] = $theme_css.$DIVISION['style'];
 if(strpos($DIVISION['title'], ',')) list($DIVISION['title'],) = explode(',', $DIVISION['title']);
 $theme_selector = (USE_THEME_CHANGER) ? theme_selector() : '';
 $pre = ($mode == 'update' || $mode == 'submit') ? '' : $DIVISION['script'];
 $DIVISION['script'] = '<script type="text/javascript" src="'.ROOT_PATH.'js/'.$js[0].'" charset="'.strtolower(ENCODE).'"></script>
 <script type="text/javascript" src="'.ROOT_PATH.'js/'.$js[1].'" charset="'.strtolower(ENCODE).'"></script>
 <script type="text/javascript" src="'.ROOT_PATH.'js/'.$js[2].'" charset="'.strtolower(ENCODE).'"></script>'.$pre;
 if(preg_match_all('{<\?php(.+?)\?>}s', $html, $mt)){ // icluding php tags
  $BUFF = array();
  ob_start();
  $length = count($mt[0]);
  $mt[1] = str_replace('@', '$', $mt[1]);
  for($i = 0; $i < $length; $i++){
   if(eval($mt[1][$i]) === FALSE){
    $BUFF[] = "ppBlog warning: parse error!";
   } else $BUFF[] = ob_get_contents();
   $html = str_replace($mt[0][$i], '$BUFF'.$i, $html);
  }
  ob_end_clean();
 }
 if(isset($BUFF)){
  for ($i = 0; $i < count($BUFF); $i++){
   $html = str_replace('$BUFF'.$i, $BUFF[$i], $html);
  }
 }
 $html = preg_replace(
  '{%_(.+?):(0|1):(.+?):(0|1)_%}e',"('$2'==1?'<h3 class=\"sidebar-cap\" title=\"$3\">'.(!$4?'<span class=\"expand-icon\" title=\"展 開！\" style=\"background-position:0px 100%;\"></span>':'<span class=\"expand-icon\" title=\"閉じる\"></span>').' $3</h3>
   <ul class=\"sidebar-body sidebar-'.strtolower('$1').'\" style=\"display:'.($4?'block':'none').';\">%_$1_%   </ul>
   <div class=\"sidebar-foot\"></div><!--#sidebar-'.strtolower('$1').'-->'.NL:'')", $html);
 $divisions = array(
  '%_BASE_%'=>ROOT_PATH,
  '%_ENCODE_%'=>ENCODE,
  '%_STYLE_%'=>$DIVISION['style'],
  '%_RSS2_%'=>$rss2,
  '%_ATOM10_%'=>$atom10,
  '%_SCRIPT_%'=>$DIVISION['script'],
  '%_LOGINFO_%'=>$DIVISION['loginfo'],
  '%_LINKBAR_%'=>$DIVISION['linkbar'],
  '%_LOGGING_%'=>(ADMIN ? $DIVISION['logout'] : $DIVISION['login']),
  '%_CONTROL_%'=>(ADMIN ? $DIVISION['control'] : ''),
  '%_SEARCH_%'=>$DIVISION['search'],
  '%_TITLE_%'=>$DIVISION['title'],
  '%_CALENDAR_%'=>$calendar,
  '%_THEME_SELECTOR_%'=>$theme_selector,
  '%_PPCOUNTER:IMAGE_%'=>$pp_counter_image,
  '%_PPCOUNTER:TEXT_%'=>$pp_counter_text,
  '%_RECENTLY_%'=>$DIVISION['recently'],
  '%_PAGES_%'=>$DIVISION['pages'],
  '%_COMMENTS_%'=>$DIVISION['comments'],
  '%_TRACKBACKS_%'=>$DIVISION['trackbacks'],
  '%_CATEGORIES_%'=>$DIVISION['categories'],
  '%_ARCHIVES_%'=>$DIVISION['archives'],
  '%_OTHERS_%'=>$DIVISION['others'],
  '%_TAGS_%'=>$DIVISION['tags'],
  '%_HEADER_%'=>$DIVISION['header'],
  '%_BODY_%'=>$DIVISION['body'],
  '&UID'=>'&amp;UID','&aim'=>'&amp;aim',
  '%_BLOGNAME_%'=>BLOG_NAME,
  '%_BLOGBAR_%'=>$blogbar,
  '%_PPBLOG_VERSION_%'=>PPBLOG_ENGINE_VERSION,
  '%_RANKING_%' => showRanking(),
  '%_TIME_%' => 'Created in '.BenchMark().' sec.',
 );
 if(is_array($_EXTRA_DIVISIONS)) $divisions += $_EXTRA_DIVISIONS;
 exit(str_replace(array_keys($divisions), array_values($divisions), $html));
}

function log_($uid){// yyyymm形式のログファイルを返す
 global $mode, $LOGS;
 if(empty($LOGS)) $LOGS = my_glob(EXT, 'log/');
 $uid = (strpos($uid, 'd') || strpos($uid, 'e')) ? substr($uid, 0, -1) : $uid;
 if($uid == '' || !is_numeric($uid)) return;
 if(!in_array(LOG.date('Ym', $uid).EXT, $LOGS) ){ // in_array is faster than file_exsits
  if($mode=='submit' || $mode=='update' || $mode=='backup'){
   mk_fl(LOG.date('Ym', $uid).EXT);
   return LOG.date('Ym', $uid).EXT;
  } else return '';
 } else return LOG.date('Ym', $uid).EXT;
}

function get_article_index($uid, $logline){ // $uidのインデックスを検出
 $uid = substr($uid, 0, 10);
 $hit = preg_grep("{^${uid}d?\|}", $logline);
 $hit = array_keys($hit);
 return !empty($hit) ? reset($hit) : -1;
}

function my_convert_encoding($string, $to, $from=ENCODE){
 if(strtolower($to)==strtolower($from) || trim($string)=='' || $to=='') return $string;
 return mb_convert_encoding($string, $to, $from);
}

function get_adjacent_article($uid){
 global $LOGS;
 $triplet = $_triplet = $lines = array(); # 0:prev, 1:self, 2:next
 $logCount = count($LOGS);
 foreach($LOGS as $i=>$log){
  if(strpos($log, date('Ym', substr($uid, 0, 10)))){
   $start = $i; break;
  }
 }
 $lines = my_file($LOGS[$start]);
 $index = array_keys(preg_grep("{^${uid}d?\|}", $lines));
 if(isset($index[0])){
  $index = $index[0];
 } else return;
 if($index > 0){
  $_triplet = array_slice($lines, $index-1, 3); // next & self set

  while(count($_triplet) < 3){ // get prev
   if($logCount-1 > $i){
    $lines = array_merge($lines, my_file($LOGS[++$i]));
    $_triplet = array_slice($lines, $index-1, 3);
   } else break;
  }
  $triplet = array_reverse($_triplet);
 } else { // $index = 0;
  $_triplet = array_slice($lines, $index, 2); // self set
  while(count($_triplet) < 2){ // get prev
   if($logCount-1 > $i){
    $lines = array_merge($lines, my_file($LOGS[++$i]));
    $_triplet = array_slice($lines, $index, 2);
   } else break;
  }
  $triplet = array_reverse($_triplet);
  if($start > 0){
   $triplet[2] = my_file($LOGS[$start-1]);
   $triplet[2] = array_pop($triplet[2]); // get next
  } else $triplet[2] = '';
 }
 $triplet = preg_replace('{^(.+?)\|.+?\|(.+?)\|.+$}','$1|$2',$triplet);
 if(count($triplet)!=3) array_unshift($triplet, ''); # Thanks naoK!
 return $triplet;
}

function article_nav($id, $keep=FALSE, $ajax=FALSE){
 global $_self;
 $triplet = get_adjacent_article($id);
 if(!empty($triplet[2])){
  list($uid, $entry) = explode('|', $triplet[2]);
  if(strpos($entry, ',')){
   list($entry, $pm_title) = explode(',', $entry); $uid = substr($uid, 0, 10);
   $pm_link = MODE_STATIC ? (WITH_DATE ? date('Ym-', $uid) : '').$pm_title.EXT_STATIC : $_self.'?UID='.$uid;
  } else $pm_link = MODE_STATIC ? $uid.EXT_STATIC : $_self.'?UID='.$uid;
  $click = $ajax ? ' onclick="loadArticle(\''.$uid.'\');return false;"' : '';
  $next_entry = '<a title="次の記事:'.date('Y-m-d', substr($uid, 0, 10)).'" href="'.$pm_link.'"'.$click.'>'.$entry.'&raquo;</a>';
 } else $next_entry = '';
 if(!empty($triplet[0])){
  list($uid, $entry) = explode('|', $triplet[0]); $uid = substr($uid, 0, 10);
  if(strpos($entry, ',')){
   list($entry, $pm_title) = explode(',', $entry);
   $pm_link = MODE_STATIC ? (WITH_DATE ? date('Ym-', $uid) : '').$pm_title.EXT_STATIC : $_self.'?UID='.$uid;
  } else $pm_link = MODE_STATIC ? $uid.EXT_STATIC : $_self.'?UID='.$uid;
  $click = $ajax ? ' onclick="loadArticle(\''.$uid.'\');return false;"' : '';
  $prev_entry = '<a title="前の記事:'.date('Y-m-d', substr($uid, 0, 10)).'" href="'.$pm_link.'"'.$click.'>&laquo; '.$entry.'</a>';
 } else $prev_entry = '';
 $_pipe = ($next_entry=='') ? '' : ' | ';
 if($ajax){
  $nav = '<p class="nav">'.$prev_entry.($ajax ? ' &nbsp;&nbsp;&nbsp;&nbsp; ' : ' | ').$next_entry.NL.'</p>'.NL;
 } else $nav = '<p class="nav">'.$prev_entry.' | <a title="トップページへ" href="'.ROOT_PATH.'">Main</a> '.$_pipe.$next_entry.NL.'</p>'.NL;
 if(!$keep){
  return $nav;
 } else {
  return array($nav, $triplet);
 }
}

### ボックス表示 ###

function show_box($id='', $comment_form=TRUE, $target='', $alone=0, $index=0, $sup_same=0, $inf_same=0, $mht=0, $ajax_list=0, $via_ajax=FALSE){
 global $DIVISION, $SESSION, $_cache, $timestamp, $cc_name, $UID, $mb, $ip, $theme_dir, $_self, $USR_LIST, $D, $mode, $CATEGORY_LIST, $RANKING, $RANKING_BACK;
 $wday = array('<span class="Sun">日</span>','月','火','水','木','金','土');
 if(empty($target)){
  if(($log=log_($id)) != ''){
   $targetLog = my_file($log, ADMIN);
   $target = preg_grep("{^($id)d?\|}", $targetLog);
   $target = reset($target);
   if(empty($target)) return $DIVISION['body'] = '<div class="alert center">その記事はないようです</div>';
  } else return;
 } else {
  if(empty($id)) list($id,) = explode('|', $target);
 }
 if(!$via_ajax){
  if($alone && !$mht){
   list($nav, $triplet) = article_nav($id, TRUE);
   $DIVISION['header'] .= ($comment_form ? $nav : '');
  }
  if(!isset($CATEGORY_LIST)) include_once (OD.'category.ini.php');
 }
 list($id,$cat,$title,$com,$author,$allowComment,$allowPing,,$extended) = explode('|', $target);

 if(!$via_ajax){
  $cat_icon = preg_grep("|$cat\t.+?\|\d+?\|\d+$|", $CATEGORY_LIST);
  if(!empty($cat_icon)){
   $cat_icon = array_values($cat_icon); $cat_icon = $cat_icon[0];
   $cat_icon = preg_replace('{^.+?\|\d+?\|}', '', $cat_icon); # icon|w|h
  } else $cat_icon = '';
 }
 if(strpos($title, ',')){
  list($_title, $pm_title) = explode(',', $title, 2);
  $pm_link = MODE_STATIC ? (WITH_DATE ? date('Ym-', substr($id, 0, 10)) : '').$pm_title.EXT_STATIC : 'index.php?UID='.$id;
 } else {
  $_title = $title;
  $pm_link = MODE_STATIC ? $id.EXT_STATIC : 'index.php?UID='.$id;
 }
 $ulink = MODE_STATIC ? $id : 'index.php?UID='.$id;

 if(!ADMIN && $UID != ''){ # 参照数ランキング用
  $ranking = OD.'ranking.ini.php';
  $lockfile = OD.'ranking.lock';
  $back = OD.'ranking.back';
  if(is_file($lockfile)){
   if($timestamp - filemtime($lockfile) > 60) unlink($lockfile);
  }
  if(is_file($ranking) && !is_file($lockfile)){
   if(!is_file($back)){
    copy($ranking, $back);
    $backup = file($back);
    $backup[0] = '<?php $RANKING_BACK = array(';
    rewrite($back, $backup);
   }
   rewrite($lockfile);
   include $ranking;
   include $back;
   $hit = preg_grep("/(\d+\t$UID\t.+?)/", $RANKING);
   if(empty($hit)){
    array_push($RANKING, "1\t$UID\t$pm_link\t$_title");
    if(sizeof($RANKING_BACK) <= sizeof($RANKING)) rewrite_ini($ranking, $RANKING);
   } else {
    $ix = array_keys($hit); $ix = $ix[0];
    list($count,) = explode("\t", $RANKING[$ix], 2);
    $RANKING[$ix] = (++$count)."\t$UID\t$pm_link\t$_title";
    rsort($RANKING, SORT_NUMERIC);
    $RANKING = array_slice($RANKING, 0, 1000);
    rewrite_ini($ranking, $RANKING);
   }
   unlink($lockfile);
  } else {
   if(!file_exists($ranking)) rewrite_ini($ranking, '', '$RANKING');
  }
 } else {
  if(ADMIN){
   $ranking = OD.'ranking.ini.php';
   $back = OD.'ranking.back';
   if(is_file($ranking)){
    include $ranking;
    list($count1,) = explode("\t", $RANKING[0], 2);
    if(is_file($back)){
     include $back;
     list($count2,) = explode("\t", $RANKING_BACK[0], 2);
     if(($count1 > $count2) || (filesize($ranking) > filesize($back))){
      unlink($back); copy($ranking, $back);
      $backup = file($back);
      $backup[0] = '<?php $RANKING_BACK = array(';
      rewrite($back, $backup);
     }
    } else copy($ranking, $back);
   }
  }
 }

 $cmts_array = get_cmt_array($id);
 if(is_file(TB_DIR.$id.EXT)){
  $tbs_array = unserialize(get_file_content(TB_DIR.$id.EXT));
 } else $tbs_array = array();
 $tb_count = sizeof($tbs_array);
 if(!empty($cmts_array)){
  $cmtInfo = array_shift($cmts_array);
  $parts = explode('|', $cmtInfo);
  $cmt_count = isOwnerLoggedIn() ? $parts[3] : (int)($parts[3] - $parts[4]);
  $_cmt_count = (int)($cmt_count + $tb_count);
 } else {
  $cmt_count = 0; $_cmt_count = $tb_count;
  $cmtInfo = $id.'|'.$cat.'|'.$title.'|0|0'.NL;
 }
 if(!empty($tbs_array)){
  for($i = 0; $i < $tb_count; $i++){
   $tb_blog_name = !empty($tbs_array[$i]['blog_name']) ? rawurldecode($tbs_array[$i]['blog_name']) : rawurldecode($tbs_array[$i]['url']);
   $tb_title = rawurldecode($tbs_array[$i]['title']);
   $tb_from = rawurldecode($tbs_array[$i]['url']);
   $tb_excerpt = rawurldecode($tbs_array[$i]['excerpt']);
   $tb_excerpt .= '<br /><a href="'.$tb_from.'"'.(ENABLE_NEW_WINDOW ? ' rel="external nofollow"' : '').'>続き &raquo;</a>';
   $tb_entry = $tbs_array[$i]['entry'];
   $cmts_array[] = $tb_entry.'|'.$tb_blog_name.'|483d8b|'.$tb_excerpt.'|-1|'.$tb_from.'|0|0|'.NL;
  }
 }
 $_cmts_array = array();
 foreach ($cmts_array as $i=>$cmt){
  list($utime,$c_name,,,$ip,) = explode('|', $cmt);
  if($c_name==$SESSION->owner() && $ip != -1){
   if($i > 0){
    list($sup_utime,) = explode('|', $cmts_array[$i-1]);
    $_cmts_array[] = $sup_utime.'}$'.trim($cmt);
   } else $_cmts_array[] = trim($cmt);
  } else $_cmts_array[] = trim($cmt);
 }
 
 usort($_cmts_array, 'SORT_BY_DATE');
 $cmts_array = array_reverse($_cmts_array);
 $_com = NL;
 if($mode != 'trackback' && $comment_form){ # トラックバック表示でないなら
  if(!empty($cmts_array)) $_com .= '<div id="responses'.($via_ajax ? '-'.$id : '').'" class="comments-div">'.NL.'<p class="comments-header">この記事に対するコメント・トラックバック ['.$_cmt_count.'件]</p>'.NL;
  $NO = $isNondiscUsr = 0;

  foreach ($cmts_array as $i => $c){
   $c_id = $c_name = $c_color = $c_com = $c_ip = $c_url = $c_nondisc = $c_mail = '';
   $p = explode('|', $c);
   $c_id = $p[0]; $c_name = $p[1]; $c_color = $p[2]; $c_com = $p[3];
   $c_ip = ($p[4] > 0) ? $p[4] : '(-)'; $c_url = !empty($p[5]) ? $p[5] : '';
   $c_mail = !empty($p[6]) ? '[<span style="color:#f35;font-size:11px;cursor: help;" title="'.my_decrypt($p[6]).'">メールアドレス登録あり</span>]' : '';
   if($p[7]==1){// 非公開指定
    if(!isOwnerLoggedIn()){
     if($c_name==ONAME){
      if(strpos($cmts_array[$i-1], "|$cc_name|") && strpos($cmts_array[$i-1], "|$ip|")){
       $isNondiscUsr = 1;
       $c_nondisc = ' non-disclosure';
      } else continue;
     } else {
      if( ($cc_name==$c_name && $ip==$c_ip) ){ // 非公開指定したユーザーっぽい
       $isNondiscUsr = 1;
      } else continue;
     }
     if($isNondiscUsr){
      $NO++;
      $c_nondisc = ' non-disclosure';
     } else continue;
    } else { // OWNERなら
     $NO++;
     $c_nondisc = ' non-disclosure';
    }
   } else $NO++;
   $extlink = ENABLE_NEW_WINDOW ? ' rel="external nofollow"' : '';
   $linkimg = ENABLE_NEW_WINDOW ? '<img class="extlink-icon" src="'.$theme_dir.'Images/external-link.png" width="12" height="12" alt="External Link" />' : '';
   $url = preg_match('{'.V_URL.'}', $c_url) ?
   ' <a href="'.$c_url.'"'.$extlink.'><img class="home-icon" src="'.$theme_dir.'Images/home.png" alt="Website" title="ホームページ" /></a>':'';
   if($p[4]==-1){ # TrackBack entry
    $cntrl = (isOwnerLoggedIn() || isRegisteredUser($author) || isRegisteredUser($c_name)) ?
   '<span class="comment-cntrl">
     <a class="delete" href="trackback.php?mode=delete&amp;UID='.$id.'&amp;TBID='.$c_id.'"
   onclick="return my_confirm(\'このトラックバックを\');"><img src="'.$theme_dir.'Images/del-comment.png" alt="Delete" title="このトラックバックの削除" /></a>
    </span>' : '';
   } else {
    if($c_name==$SESSION->owner()){
     if(strpos($c_id, '}$')) list(,$c_id) = explode('}$', $c_id);
    }
    $cntrl = (isOwnerLoggedIn() || isRegisteredUser($author) || isRegisteredUser($c_name)) ?
   '<span class="comment-cntrl">
    <a  href="admin.php?mode=edit_comment&amp;UID='.$id.'&amp;CID='.$c_id.'"><img src="'.$theme_dir.'Images/edit-comment.png" alt="Edit" title="このコメントの編集" /></a>
    <a  href="admin.php?mode=delete_comment&amp;UID='.$id.'&amp;CID='.$c_id.'" onclick="return my_confirm(\'このコメントを\')"><img src="'.$theme_dir.'Images/del-comment.png" alt="Delete" title="このコメントの削除" /></a>
    <a href="admin.php?mode=res_comment&amp;UID='.$id.'&amp;CID='.$c_id.'"><img src="'.$theme_dir.'Images/reply.png" alt="Reply" title="このコメントに返事を書く" /></a>
    </span>' : '';
   }
   $c_com = preg_replace('{\[q\]`?(.+?)`?\[/q\]`?}is', NL.'<p class="comment-quote">\\1</p>'.NL, $c_com);
   $c_com = str_replace('`', '<br />', $c_com);
  
   if($c_name==$SESSION->owner()){
    $_com .= ' <div class="comment-entry-owner">
  <p class="comment-index-owner">'.($i%5==0 ? '<a class="jump" title="ページの先頭へ" href="#weblog"><img src="'.$theme_dir.'Images/jump.png" alt="Up" /></a>':'').'<a id="CID'.$c_id.'" href="'.$ulink.'#CID'.$c_id.'"><img src="'.$theme_dir.'Images/owner-comment.png" title="Permalink" alt="Owner Comment" /></a> '.$c_name.$url.' &nbsp;'.date('Y/m/d@H:i:s', $c_id).' '.$cntrl.'</p>
 <div class="comment-body" style="color:#'.$c_color.';">'.$c_com.'</div>
</div>
';
   } else {
    $w = $p[4]==-1 ? 'TID' : 'CID';
    $_com .= ' <div class="comment-entry'.($p[4]==-1?' trackback-entry':'').$c_nondisc.'">
  <p class="comment-index">'.($i%5==0 ? '<a class="jump" href="#weblog"><img title="ページの先頭へ" src="'.$theme_dir.'Images/jump.png" alt="Up" /></a>':'').'<a class="No" id="'.$w.$c_id.'" title="Permalink" href="'.$ulink.'#'.$w.$c_id.'">'.$NO.'.</a> '.$c_name.$url.' &mdash; '.date('Y/m/d@H:i:s', $c_id).(ADMIN?' &nbsp;IP: '.$c_ip.' '.$c_mail:'').(!empty($c_nondisc) ? '<sup>このコメントや管理者の返答は非公開になってます.</sup>' : '').'</p>
 <div class="comment-body" style="color:#'.$c_color.';">'.$c_com.' '.$cntrl.'</div>
</div><!--#'.($p[4]==-1?'trackback':'comment').'-entry-->
';
   }
   $_com .= '<hr class="comment-separator" />'.NL;
  } # foreach
  if(COMMENT_AUTO_SUSPEND && COMMENT_APPEND_SPAN * 86400 < (time() - substr($id, 0, 10))){ 
   $allowComment = 0;
  }
  if(!$allowComment){
   $_com .= ENABLE_COMMENT ? '<p class="comment-closed">この記事に対する'.($_cmt_count>=1?'これ以上の':'').'コメントはありません</p>'.NL : '';
  }
  if(USE_SMILEY==TRUE) $_com = convert_smilies($_com);
  $_com = autolink($_com);
  if($via_ajax) return $_com.($allowComment ? '<div class="cute-button cute-reply" onclick="loadCommentForm('.$id.');"><button title="コメントフォームを表示します">コメントする</button></div></div><!--#responseUID-->' : '</div><!--#responseUID-->').NL;
  if($_cmt_count >= 1 || !empty($cmts_array)) $_com .= '</div><!--#responses-->'.NL;
  if($allowComment){
   include_once 'modules/comment.inc.php';
   $_com .= comment_form($id, TRUE);
  }
 } # トラックバック表示でないなら

 if(!empty($extended)){
  $pages = explode(',', $extended);
  $pageNum = count($pages) + 1; # ページ数ゲット
 } else $pages = 0;
 if($UID != ''){
  $page = g_('page') != '' ? g_('page') : 1;
 } else $page = 1;
 if($page > 1) $com = $pages[$page-2];

 $DIVISION['title'] = $title;

 if(isset($pageNum)){ # 次ページありなら
  $nav = '
  <div class="article-pageNav">
   <span class="page-stat" title="この記事は'.$pageNum.'ページあります">'.$page.' of '.$pageNum.'</span>';
  for ($i=1; $i <= $pageNum; $i++){
   if($i==$page){
    $nav .= '<span class="page-cur">'.$i.'</span>';
   } else {
    $nav .= '<span class="page-cell"><a '.(AJAX_COMPAT?' onclick="loadPage(\''.substr($id,0,10).'\','.$i.');return false;"':'').' href="'.$pm_link.'&amp;page='.$i.'" title="この記事の'.$i.'ページ目">'.$i.'</a></span>';
   }
  }
  $next = ($page < $pageNum) ?
   '<span class="page-next"><a'.(AJAX_COMPAT?' onclick="loadPage(\''.substr($id,0,10).'\','.($page+1).');return false;"':'').' href="'.$pm_link.'&amp;page='.($page+1).'" title="この記事の次ページ">Next&raquo;</a></span>' : '';
  $nav .= $next.NL;
  $nav .= '</div>'.NL;
 } else $nav = '';
 $com = ((mb_strlen($com) > ($mb?720:1400)) ? str_replace('class="article-pageNav"', 'class="article-pageNav heading-pageNav"', $nav) : '').$com.'``<!--END-->'.$nav.NL;
 if($comment_form) $alone = 1;
 $body = _box($id,$cat,$title,$com,$author,$sup_same,$inf_same,array($cmt_count,$allowComment),array($tb_count,$allowPing),$cat_icon,$alone,$index,$mht,$ajax_list).$_com.NL;
 if($comment_form){
  return $DIVISION['body'] .= $body;
 } else return $body;
}

## ボックス表示（マルチ）##

function show_box_all($LINES = ''){
 global $_self, $page, $mode, $displayMode, $displayNumber, $theme, $theme_dir, $LOGS, $CATEGORY_LIST, $DIVISION, $USR_LIST, $D;
 if(g_('view')=='list' || $displayMode == 'list') return show_lists($LINES);
 $back = '
  <div class="cute-button" style="margin-left: 47%;">
   <button onclick="history.go(-1);this.blur();" title=" 前に戻る "> Back </button>
  </div>
 ';
 if($LINES == ''){
  list($header, $LINES) = page_info('', $displayNumber);
  if(empty($LINES)) return $DIVISION['body'] .= $header.(empty($LOGS) ? '' : $back).NL;
 } elseif(empty($LINES)){
  if($mode == 'category' && SEE_CAT_HIERARCHY) $add = '<br />サブカテゴリーの記事は個別に見て下さい。'; else $add = '';
  $DIVISION['body'] .= '<p class="alert" style="margin: 50px auto;">エントリーはないようです'.$add.'</p>';
  return $DIVISION['body'] .= $back.NL;
 } else {
  list($header, $LINES) = page_info($LINES);
 }
 $length = count($LINES);
 if(($length==1 && $page=='') || ENTRY_BOX == 1) return show_box('', TRUE, $LINES[0], 1);
 $DIVISION['header'] .= $header;
 $body = '';
 foreach ($LINES as $i=>$line){
  list($id, ) = explode('|', $line, 2);
  $sup_same = $inf_same = 0;
  if($i===0 && isset($LINES[1])){
   list($inf_id,) = explode('|', $LINES[1], 2);
   $inf_same = date('Ymd', substr($id, 0, 10))==date('Ymd', substr($inf_id, 0, 10)) ? 1 : 0;
  }
  if($i===($length-1) && isset($LINES[$i-1])){
   list($sup_id,) = explode('|', $LINES[$i-1], 2);
   $i = 'LAST';
   $sup_same = date('Ymd', substr($id, 0, 10))==date('Ymd', substr($sup_id, 0, 10)) ? 1 : 0;
  }
  if($i > 0 && $i < $length-1){
   list($sup_id,) = explode('|', $LINES[$i-1], 2);
   list($inf_id,) = explode('|', $LINES[$i+1], 2);
   $sup_same = date('Ymd', substr($id, 0, 10))==date('Ymd', substr($sup_id, 0, 10)) ? 1 : 0;
   $inf_same = date('Ymd', substr($id, 0, 10))==date('Ymd', substr($inf_id, 0, 10)) ? 1 : 0;
  }
  $body .= show_box($id, FALSE, $line, FALSE, $i, $sup_same, $inf_same);
 }
 return $DIVISION['body'] = $body.NL.str_replace('asort1', 'asort2', $header).NL;
}

## リスト表示 ##

function show_lists($lines = ''){
 global $_self, $mode, $DIVISION, $D, $LOGS;
 list($header, $LINES) = page_info($lines, ENTRY_LIST);
 if(empty($LINES)){
  if($mode == 'category' && SEE_CAT_HIERARCHY) $add = '<br />サブカテゴリーの記事は個別に見て下さい。'; else $add = '';
  return $DIVISION['body'] .= '<p class="alert" style="margin: 50px auto;">エントリーはないようです'.NL.$add.'</p>';
 }
 $DIVISION['header'] .= $header;
 $body = '<div class="show-list"><ul>'.NL;
 foreach ($LINES as $line){
  list($id,$cat,$title,$com,$author,$allowComment,$allowPing,) = explode('|', $line);
  $closed = '';
  if(ADMIN != TRUE){
   $_id = $id;
   if(isset($id[10])) continue;
  } else {
   if(isset($id[10])) $closed = ' <sup>未公開</sup>';
   $_id = substr($id, 0, 10);
  }
  if(strpos($title, ',')){
   list($title, $pm_title) = explode(',', $title, 2);
   $pm_link = MODE_STATIC ? (WITH_DATE ? date('Ym-', $_id) : '').$pm_title.EXT_STATIC : 'index.php?UID='.$id;
  } else $pm_link = MODE_STATIC ? $id.EXT_STATIC : 'index.php?UID='.$id;
  $comment_num = get_cmt_array($id, TRUE);
  $comment_num = ($allowComment||$comment_num) ? '('.$comment_num .')' : '';
  $trackback_num = $allowPing ? '('.get_tb_count($id).')' : '';
  $cat = (g_('mode')=='category') ? '' : '<span class="category" title="カテゴリー">'.str_replace(',', ' &raquo; ', $cat).'</span>,';
  $body .= '   <li><a href="'.$pm_link.'" title="エントリー: '.date('Y&#24180;n&#26376;j&#26085 g:iA', $_id).'"'.(LIST_AJAX_MODE ?' onclick=\'loadArticle("'.$id.'");return false;\'':'').'>'.$title.$closed.'</a> &mdash; '.$cat.' <span class="date">'
        .date('F d, Y', $_id).'</span> <span title="コメント数">'.$comment_num.'</span> <span title="トラックバック数">'.$trackback_num.' </span></li>'.NL;
 }
 $body .= '</ul></div>'.NL;
 return $DIVISION['body'] = $body.NL.str_replace('asort1', 'asort2', $header).NL;
}

## ヘッドライン表示 ##

function show_headline($lines=''){
 global $_self, $mb, $mode, $CATEGORY_LIST, $DIVISION, $USR_LIST, $D, $LOGS;
 $blockLevel = 'div|pre|ol|ul|dl|li|dt|dd|form|blockquote|fieldset|table|tr|td|p|center|object|h[r123456]|!';
 include_once (OD.'category.ini.php');
 list($header, $LINES) = page_info($lines, ENTRY_HEADLINE);
 if(empty($LINES)){
  if(!ADMIN){
   return $DIVISION['body'] = '<p class="alert">エントリーはまだのようです...</p>';
  } else {
   return $DIVISION['body'] = '<p class="alert">エントリーはまだです. 新規投稿は管理画面から.</p>';
  }
 }
 if(count($LINES)==1) return show_box('', TRUE, $LINES[0], 1);
 $DIVISION['header'] .= $header;
 $body = '<div class="headline">'.NL;
 foreach ($LINES as $line){
  list($id,$cat,$title,$com,$author,$allowComment,$allowPing,) = explode('|', $line);
  $cmt_count = get_cmt_array($id, TRUE);
  $tb_count = $allowPing ? get_tb_count($id) : 0;
  $cat_icon = preg_grep("|$cat\t.+?\|\d+?\|\d+$|", $CATEGORY_LIST);
  if(!empty($cat_icon)){
   $cat_icon = array_values($cat_icon); $cat_icon = $cat_icon[0];
   $cat_icon = preg_replace('{^.+?\|\d+?\|}', '', $cat_icon); # icon|w|h
  } else $cat_icon = '';
  if(strpos($com, '<!--]]-->')){ // 指定表示モード
   list($com,) = explode('<!--]]-->', $com, 2); $alone = 0;
  } else {
   $com = preg_replace('/\[(?:style|script)\].*\[\/(?:style|script)\]/is', '', $com);
   $com = preg_replace('{<('.$blockLevel.')([^>]*?)>(.*?)(</\1>)}ise', "'<$1$2>'.str_replace('`', NL, '$3').'$4'.NL", $com);
   $com = preg_replace('{<!\-\-AMAZON:.+?\-\->.+?<!\-\-/AMAZON:.+?\-\->}', '$PIX$', $com);
   $com = strip_tags($com); $com = ENABLE_BR ? str_replace('``', '', $com) : $com;
   $str_len = $mb ? mb_strlen($com) : strlen($com);
   $com = preg_replace('{\[(?:media|mov):.+?/\]|<img[^>]+?>}i', '$PIX$', $com);
   $com = preg_replace('{\[(?:yt|gv|sb|nc|et|wm|av|mm|pv|ab):.+?\]}', '$PIX$', $com);
   $com = preg_replace('{(<p>|)<!--HIDE-->(.+?)(<!--/HIDE-->(</p>|)|$)}s', '', $com);
   if($str_len < STRLEN_HEADLINE){
    if(strstr($com, '$PIX$')){
     $com = str_replace('$PIX$', '', $com);
    }
    if(trim(str_replace('`', '', $com)) != '') $com .= '<!--]]-->';
   } else $com = my_substr(str_replace('$PIX$', '', $com), 0, STRLEN_HEADLINE);
   if(strstr($com, '<div class="corner-play')){
    if(!preg_match('{<div class="corner-play[^>]*>([</>]+?)</div>}', $com)) $com = $com.'</div>';
   }
  }
  $body .= _box($id,$cat,$title,$com,$author,0,0,array($cmt_count,$allowComment),array($tb_count,$allowPing),$cat_icon, 0);
 }
 $body .= '</div><!--headline-->'.NL;
 return $DIVISION['body'] = $body.NL.str_replace('asort1', 'asort2', $header).NL;
}

function page_info($LINES='', $length=ENTRY_BOX){ // これもキモ
 global $path, $_cache, $page, $date, $mode, $D, $_self, $_asort, $apres, $theme_dir, $displayMode, $displayNumber, $DIVISION;

 $date = isset($date) ? $date : g_('date');
 if(MODE_STATIC){
  $link = ROOT_PATH.$path;
  if($path != ''){
   if(preg_match('{page/\d+/(list|/box|)$}', $path, $mt)){
    $link = $link.str_replace($mt[0], '', $path);
   }
  }
  $list = ROOT_PATH.str_replace(array('/list', '/box'), '', $path).'list';
  $box = ROOT_PATH.str_replace(array('/list', '/box'), '', $path).'box';
 } else {
  $query = str_replace(array('?view=box','&amp;view=box','?view=list','&amp;view=list'), '', QUERY);
  $query = preg_replace('{(&amp;)?page=\d+}', '', $query);
  $link = 'index.php?'.$query;
  $list = ($link == 'index.php?') ? 'index.php?view=list' : $link.'&amp;view=list';
  $box = str_replace('list', 'box', $list);
 }
 $pitch= $displayMode == 'box' ? $displayNumber : ENTRY_LIST;
 $offset = $pitch * ($page - 1);
 if($LINES==''){
  if($date != ''){ // date is set
   if(log_($D[0]) != ''){ // log file is.
    $_lines = strlen($date) == 8 ? get_articles_by_date($date) : my_file(log_($D[0]));
    $total = count($_lines);
    if($_asort != 'descend') $_lines = array_reverse($_lines);
    $LINES = array_slice($_lines, $offset, $length);
   } else {
    return array('<h3 class="alert">'.$D['year'].'年'.$D['mon'].'月のエントリーはありません。</h3>'.NL, '', TRUE);
   }
  } else { // date is NOT set
   $LINES = get_sliced_articles($offset, $length, $_asort);
   $total = isOwnerLoggedIn() ? $_cache['total_articles_count']['real'] : $_cache['total_articles_count']['nominal'];
  }
 } else {
  $total = count($LINES);
  if($_asort != 'descend') $LINES = array_reverse($LINES);
  $LINES = array_slice($LINES, $offset, $length);
 }
 if(empty($LINES)){
  return array('<h3 class="center">記事はないようです。</h3>', '', TRUE);
 }
 
 $header = '<div class="nav">'.NL;
 $main = '<a href="'.ROOT_PATH.'" title="メインページへ">Main</a>';
 $box_view = ' <strong>ボックス表示</strong> &hArr; <a href="'.$list.'" title="リスト表示に切り替えます">リスト表示</a>'.NL;
 $list_view = ' <strong>リスト表示</strong> &hArr; <a href="'.$box.'" title="ボックス表示に切り替えます">ボックス表示</a>'.NL;
 $box_only = '表示 &raquo; '.$main.NL;
 if($total >= 1){
  $header .= empty($date) ? '' : $D['year'].'年'.$D['mon'].'月'.($mode=='show'?$D['mday'].'日の':'の');
  $header .= "エントリー ".$total.' 件中 '.($offset+1)."-".($offset+$length > $total ? $total : $offset+$length).' 件を';
  if($displayMode=='list'){
   $header .= $list_view;
  } else {
   $header .= $box_view;
  }
 }

 if(defined('ENABLE_INVERSE_SORT') && ENABLE_INVERSE_SORT){
  $header .= '<form id="asort1" action="'.$link.'" method="post" style="display:inline;">
 <p>
  <input type="hidden" name="view" value="'.$displayMode.'" />
  <label title="日付の新しい順に記事を表示"><input type="radio" name="_asort"'.($_asort=='descend'?' checked="checked"':'').' value="descend"
   onclick=\'o("#asort1").$.submit();\' /> 新しい順 </label>&nbsp;&nbsp;
  <label title="日付の古い順に記事を表示"><input type="radio" name="_asort"'.($_asort=='ascend'?' checked="checked"':'').' value="ascend"
   onclick=\'o("#asort1").$.submit();\' /> 古い順 </label>'.(
   (defined('ENABLE_USER_SELECT') && ENABLE_USER_SELECT) ? '&nbsp;&nbsp;
  <label>表示記事の数 <input type="text" size="2" name="displayNumber" value="'.$displayNumber.'" /></label>
  <input type="image" src="'.$theme_dir.'Images/search-button.png" style="vertical-align: top;" alt="Set" />' : '').'
 </p>
 </form>'.NL;
 }

 $pages = ceil($total/$pitch);
 $pageBlock = ceil($page / 10);
 if(MODE_STATIC){
  $pagelink = 'page'.$apres; 
 } else $pagelink = ($query == '' ? '' : '&amp;').'page=';
 if($pages==1){
  $pageNav = '';
 } else {
  $pageNav = '<div class="weblog-pageNav">';
  if($page > 1) $pageNav .= '<a class="prev" href="'.$link.$pagelink.($page - 1).$apres.'">&laquo;前へ</a>';
  if($pages > 10 && ($pageBlock-1)*10 > 0 ){
   $pageNav .= '<a href="'.$link.$pagelink.(($pageBlock-1)*10).$apres.'">
   '.($pB=($pageBlock-2)*10+1).'-'.($pages > $pB+9 ? $pB+9 : $pB+$pages%10-1).'</a>';
  }
  for ($i=($pageBlock-1)*10+1; $i <= $pages; $i++){
   if($i==$page){
    $pageNav .= '<span class="current">'.$i.'</span>';
   } else {
    $pageNav .= '<a href="'.$link.$pagelink.$i.$apres.'">'.$i.'</a>';
   }
   if($i%10 == 0) break;
  }
  if($pages > 10 && $pages > $pageBlock*10){
   $pageNav .= '<a href="'.$link.$pagelink.($pageBlock*10+1).$apres.'">
   '.($pB=$pageBlock*10+1).'..'.($pages >= $pB+9 ? $pB+9 : $pB+$pages%10-1).'</a>';
  }
  if($page < $pages){
   $pageNav .= '<a class="next" href="'.$link.$pagelink.($page+1).$apres.'">次へ&raquo;</a>';
  }
  $pageNav .= '</div>'.NL;
 }
 $header .= $pageNav.'</div><!--#nav-->'.NL;
 return array($header, $LINES);
}
function my_parser($string, $br_enabled=FALSE){ // revised in v1.7.8
 global $DIVISION, $ESCAPE;
 $blockLevel = 'div|pre|ol|ul|dl|li|dt|dd|form|blockquote|fieldset|table|thead|tbody|th|tr|td|p|center|object|h[r123456]|!';
 $_blockLevel = str_replace('|', '|<', $blockLevel);
 if(!$br_enabled){ // 強制改行なし(デフォルト)
  $string = preg_replace( // Block-levelの中の改行記号は削除
            '{<('.$blockLevel.')([^>]*?)>(.*?)(</\1>)}ise', // s is point
            "'<$1$2>'.str_replace('`', NL, '$3').'$4'.NL", $string);
  $strings = explode('``', $string);
  $_string = '';
  foreach ($strings as $st){
   if(trim($st)=='') continue;
   if(!preg_match('{<'.$_blockLevel.'}i', $st)){
    $_string .= '<p>'.$st.'</p>'.NL;
   } else $_string .= $st;
  }
  return str_replace(array('\"', '`', '&#44;'), array('"', '', ','), ltrim($_string));
 } else { // 強制改行有効
  $string = preg_replace( # ブロック前後の`(改行)は消去(\n)
            '{(`[[:space:]]*?)</('.$blockLevel.')>}i',
            NL.'</$2>', $string);
  $string = preg_replace(
            '{<(/?)('.$blockLevel.')([^>]*?)>([[:space:]]*?`)}i',
            '<$1$2$3>'.NL, $string);
  $string = preg_replace( // PREタグの中の改行記号は削除
            '{<(pre)([^>]*?)>(.*?)(</\1>)}ise', // s is point
            "'<$1$2>'.str_replace('`', NL, '$3').'$4'", $string);
  return preg_replace('/(.*?)`/','$1<br />'.NL, str_replace(array('\"', '&#44;'), array('"', ','), $string));
 }
}

function _box($id,$cat,$title,$com,$author='',$sup_same=0,$inf_same=0,$cmtInfo=array(0,1),$tbInfo=array(0,1),$cat_icon='',$alone=0,$index=0,$mht=0,$ajax_list=0){ // これもキモ
 global $ua,$hd,$mb,$apres,$theme,$mode,$_timestamp,$UID,$RANKING,$_self,$theme_dir,$displayNumber,$CATEGORY_LIST,$SESSION,$_ARTCL_BOX_UNITED,$_ARTCL_BOX_FORMAT,$DIVISION;
 $draft_mode = strpos($id, 'd') ? 1 : 0;
 $_id = substr($id, 0, 10);
 $ontime = (ADMIN && isset($_timestamp) && ($_id > $_timestamp)) ? TRUE : FALSE;
 if(strpos($title, ',')){
  list($title, $pm_title) = explode(',', $title, 2);
  $pm_link = MODE_STATIC ? (WITH_DATE ? date('Ym-', substr($id, 0, 10)) : '').$pm_title.EXT_STATIC : 'index.php?UID='.$id;
 } else $pm_link = MODE_STATIC ? $id.EXT_STATIC : 'index.php?UID='.$id;
 $RDF = (EMBED_TRACKBACK_RDF && !$mht) ? put_RDF($_id, $title, $cat, $com, $author) : '';
 $reviews = '';
 if(ADMIN && SHOW_REVIEW_COUNT && !$draft_mode && is_file(($ranking = OD.'ranking.ini.php'))){
  include_once $ranking;
  $hit = preg_grep("/(\d+\t$_id\t.+?)/", $RANKING);
  if(!empty($hit)){
   $ix = array_keys($hit); $ix = $ix[0];
   list($views,) = explode("\t", $RANKING[$ix], 2);
   $reviews = ' <sup style="font-size:x-small;color:#aaa;" title="記事の参照数です">'.$views.'</sup>';
  }
 }

 if(strpos($com, '[escape]')){
  $escaped = preg_match('{\[escape\].+?\[/escape\]}s', $com, $mt);
  if($escaped){
   $escaped = $mt[0];
   $com = str_replace($escaped, '[ESCAPED]', $com);
  }
 }

 if(strstr($com, '[script]') && preg_match_all('{\[script\](.+?)\[/script\]}', $com, $mt)){
  $prev = '  '; $rep = array('&#36;' => '$', '`'=>NL, '&#37;'=>'%', '&#44;'=>',', NL=>NL.'  ', '&yen;'=>'\\');
  foreach ($mt[1] as $m) $prev .= str_replace(array_keys($rep), array_values($rep), $m);
  $com = str_replace($mt[0], '', $com);
  if($ajax_list){
   $DIVISION['script'] .= '[script]'.trim($prev).'[/script]';
  } else $DIVISION['script'] .= ' <script type="text/javascript">'.rtrim($prev).NL.' </script>';
 }

 if(strstr($com, '[style]') && preg_match_all('{`?\[style\](.+?)\[/style\]`?}', $com, $mt)){
  $prev = '';
  $rep = array("#UID$id"=>'', '`'=>NL, '&#37;'=>'%', '&#44;'=>',', NL=>NL.'  ', '&yen;'=>'\\');
  foreach ($mt[1] as $m){
   $prev .= str_replace(array_keys($rep), array_values($rep), $m);
   preg_match('|([^{\n]+?)([{])|me', $m, $mtt);
   $prev = preg_replace('|([^{\n]+?)({)|me', "'   #UID$id '.trim('$1').('$2'=='{' ? ' ' : '').trim('$2').''", ltrim($prev));
  } 
  $com = str_replace($mt[0], '', $com);
  if($ajax_list){
   $DIVISION['script'] .= '[style]'.rtrim($prev).'[/style]';
  } else $DIVISION['script'] .= NL.' <style type="text/css">'.NL.rtrim($prev).NL.' </style>';
 }
 if(preg_match_all('{<img src="([^"]+?)" alt="([^"]*?)"(.*?)/>}i', $com, $mt)){ // icluding image-tags
  $length = count($mt[0]);
  for($i=0; $i < $length; $i++){
   if(!is_file(PATH.$mt[1][$i])){
    $com = str_replace($mt[0][$i], '<p class="al-right"><img src="Images/notfound.png" alt="404 File Not Found" /></p>', $com);
   } else { // E
    $_img = basename($imgf=$mt[1][$i]); $photo_effect = trim($mt[3][$i]) != '' ? 1 : 0;
    $imgName = str_replace($id.'_', '', $_img);
    list($fs,$w,$h,$tw,$th,$alt,$align,$shadow,$border,$caption,$polaroid) = explode(':', $mt[2][$i]);
    $caption = ($caption == '[caption]') ? '' : $caption;
    if($border){
     $polaroid = trim($polaroid) == '' ? PICTURE_POLAROID : $polaroid;
    } else $polaroid = 0;
    if($polaroid && $shadow && $border && $caption != ''){
     $_wrap = '</div></div>'.NL; $_div = NL;
    } else { $_wrap = '</div>'.NL; $_div = '</div>';}
    $_border = ($photo_effect || $border) ? ' ' : ' class="borderless" ';
    $_shadow = ($shadow && !$photo_effect) ? ' <div class="shadow">' : ' <div class="noshadow">';
    $fs = ($fs > 1024) ? sprintf('%01.2f', $fs/1024).'MB' : $fs.'KB';
    $info = '　　ファイル名: '.$imgName.'&#13;&#10;ファイルサイズ: '.$fs;
    $thumb = is_file(IMG_DIR.THUMB2.$_img) ? IMG_DIR.THUMB2.$_img : 'Images/notfound.png';
    $img = ($tw * $th > 0) ? 'src="'.$thumb.'"' : 'src="'.IMG_DIR.$_img.'"';
    $wrapw = $tw > 0 ? $tw : $w; $wrapw = $border ? $wrapw + 9 : $wrapw;
    $photocap = $caption=='' ? '<hr class="clear" />' : ' <div class="photo-caption" style="width: '.($wrapw - 9).'px;">'.$caption.'</div>';
    $div = NL.'<div class="'.(!$photo_effect ? ($_div == NL ? 'polaroid' : 'photo').' ' : '');
    $wrap = $div.'al-'.$align.'" style="width: '.$wrapw.'px;">'.NL.$_shadow;
    if($tw > 0){ // resized image is.
     if($_border == ' '){
      $rest = strstr($mt[3][$i], 'class="') ? preg_replace('{class="(.+?)"}', 'class="\\1 resized"', $mt[3][$i]) : $mt[3][$i].' class="resized"';
     } else {
      $_border = ' ';
      $rest = strstr($mt[3][$i], 'class="') ? preg_replace('{class="(.+?)"}', 'class="\\1 resized"', $mt[3][$i]) : $mt[3][$i].' class="borderless resized"';
     }
     $com = str_replace($mt[0][$i],
      $wrap.'<img'.$_border.$img.' title="'.$info.'&#13;&#10;&#13;&#10;　→クリックで元のサイズを表示" width="'.$tw.'" height="'.$th.'" alt="'.$alt.'" onclick="imagePop(this, \''.IMG_DIR.$_img.'\', '.$w.', '.$h.');"'.$rest.' />'.$_div.$photocap.$_wrap.'`', $com);
    } else { // $tw == 0; resized image is NOT.
     $com = str_replace($mt[0][$i],
      $wrap.'<img'.$_border.$img.' title="'.$info.'" width="'.$w.'" height="'.$h.'" alt="'.$alt.'"'.$mt[3][$i].' />'.$_div.$photocap.$_wrap.'`', $com);
    }
   } // E
  }
 }
 // 動画ファイル表示処理
 if(preg_match_all('{\[(?:media|mov):([^:]+?):([^:]+?)(:[^\]]+?|)/\]}', $com, $movs)){
  $length = count($movs[0]);
  for($i=0; $i < $length; $i++){
   $movies = '';
   $_file = $movs[1][$i];
   $_filetype = isset($movs[3][$i]) ? str_replace(':', '', $movs[3][$i]) : 'video/3gpp';
   if($_filetype == 'pch' && is_file('modules/PCHViewer.jar')){ # PCH animation
    if(is_file(DB.$_file) && !is_file(MEDIA_DIR.$_file)){
     copy(DB.$_file, MEDIA_DIR.$_file);
     unlink(PATH.DB.$_file);
    }
    if(is_file(MEDIA_DIR.$_file)){
     $movies = '
   <div class="media-part" style="width: '.$movs[2][$i].'px;">
    <applet name="pch" code="pch2.PCHViewer.class" codebase="./" archive="modules/PCHViewer.jar" width="100%" height="'.$movs[2][$i].'">
     <param name="speed" value="1" />
     <param name="res.zip" value="modules/res.zip">
     <param name="run" value="false" />
     <param name="buffer_progress" value="false" />
     <param name="buffer_canvas" value="false" />
     <param name="quality" value="1" />
     <param name="pch_file" value="'.MEDIA_DIR.$_file.'" />
    </applet>
   </div><!--#media-->'.NL;
    }
   } else {
    $_fname = str_replace($id.'_', '', $_file);
    $_fsize = $movs[2][$i].'KB';
    $_movf = MEDIA_DIR.$_file;
    if(preg_match('/mode=show|UID/', QUERY)){
     if(preg_match('{3gp|x-mpeg}i', $_filetype)){ # 3gpp or amc
      $clsid = preg_match('/msie|sleipnir|lunascape/i', $ua) ?
     'classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
      codebase="http://www.apple.com/qtactivex/qtplugin.cab"' : 'type="video/3gpp" data="'.$_movf.'"';
     } else $clsid = 'type="'.$_filetype.'" data="'.$_movf.'"';
     $movies = '
    <div class="media-part">
     <h6 title="動画へダイレクトリンク">::<a class="media-link" href="'.$_movf.'">'.$_fname.'('.$_fsize.')</a>::</h6>
     <object '.$clsid.' width="176" height="160">
      <param name="type" value="'.$_filetype.'" />
      <param name="src" value="'.$_movf.'" />
      <param name="autoplay" value="false" />
     </object>
    </div><!--#media-->'.NL;
    } else {
     $movies = NL.'    <div class="attached">'.NL;
     $movies .= '<a href="'.$_movf.'" title="'.$_fname.' '.$_fsize.'：この場で再生"
      onclick="loadMedia(this,\''.$_movf.'\',\''.$_filetype.'\');return false;"><img src="'.$theme_dir.'Images/media.png" style="margin:0;vertical-align:middle;" alt="" /> '.$_fname.'</a></div>'.NL;
    }
   }
   $com = str_replace($movs[0][$i], $movies, $com);
  }
 }
 
 // 添付ファイル表示処理
 if(preg_match_all('{\[file:([^:]+?):([^/]*?)/\]}', $com, $files)){
  if(ADMIN == TRUE){
   if(is_file(($logfile = OD.'dl_count.log'))){
    $logfile = file($logfile);
   }
  }
  $attached = '<div class="attached">'.NL.'添付ファイル： ';
  $length = count($files[0]);
  for($i=0; $i < $length; $i++){
   $dl_count = $dl_hit = '';
   $_file = $files[1][$i];
   $_fname = str_replace($id.'_', '', $_file);
   if(strpos($_file, 'NONALNUM-')){
    list($_fname, $_fext) = explode(".", $_fname);
    $_fname = url_decode(str_replace('NONALNUM-', '', $_fname)).$_fext;
   }
   $_fsize = ($files[2][$i] < 1000) ? $files[2][$i].'KB' : round($files[2][$i]/1000,2).'MB';
   if(ADMIN == TRUE){
    $dl_hit = preg_grep('{'.$_file.'}', $logfile);
    if(!empty($dl_hit)){
     $dl_hit = array_shift($dl_hit);
     list(,,$dl_count) = explode('|', $dl_hit); $dl_count = ' <span title="ダウンロード数">[DL:'.trim($dl_count).']</span>';
    } else $dl_couunt = '';
   } else $dl_count = '';
   $attached .= '<a title="" href="index.php?mode=download&amp;aim='.$_file.'">'.$_fname.'<img class="attached-icon" src="'.$theme_dir.'Images/attached.png" title="　　ファイル名: '.$_fname.'&#13;&#10;ファイルサイズ: '.$_fsize.'" alt="" /></a>'.$dl_count.'&nbsp;'.NL;
   
   $com = str_replace($files[0][$i], '', $com);
  }
  $attached .= '</div>'.NL;
  $com = str_replace('<!--END-->','<!--END-->'.$attached, $com);
 }
 // 外部動画リンク表示処理 (YouTube, Google Video,...)
 if(preg_match_all('{\[(yt|gv|nc|wm|mm|pv):([^:]+?):(\d+?|):(\d+?|)\]}i', $com, $movlinks)){
  $length = count($movlinks[0]);
  $embeds = array( # src, type, others, width/height
   'yt' => array('http://www.youtube.com/v/', 'application/x-shockwave-flash', '', '425,350'),
   'gv' => array('http://video.google.com/googleplayer.swf?docId=', 'application/x-shockwave-flash', 'id="VideoPlayback"', '400,300'),
   'nc' => array('http://www.nicovideo.jp/thumb?v=', 'IFRAME', '', '312,176'),
   'wm' => array('http://www.watchme.tv/p/video_output.swf?mid=', 'application/x-shockwave-flash', '', '339,300'),
   'mm' => array('http://mooom.jp/P320x240.swf?m=', 'application/x-shockwave-flash', 'wmode="transparent" quality="high" scale="noscale"', '320,240'),
   'pv' => array('http://peevee.tv/pluginplayerv4.swf?video_id=', 'application/x-shockwave-flash', '', '333,298'),
  );
  for($i=0; $i<$length; $i++){
   $_mv = NL.'<div class="video-link">'.NL;
   $vendor = $movlinks[1][$i]; $src = $movlinks[2][$i];
   $tar = $embeds[$vendor];
   list($def_w, $def_h) = explode(',', $tar[3]);
   $w = $movlinks[3][$i]=='' ? $def_w : $movlinks[3][$i];
   $h = ($h=$movlinks[4][$i])=='' ? ($movlinks[3][$i]=='' ? $def_h : ceil($w * .75)) : $h;
   if($tar[1]=='IFRAME'){
    $css = ' style="width:'.$w.'px; height:'.$h.'px;border:solid 1px #ddd;" ';
    if(IE){
     $_mv .= ' <script type="text/javascript">d.write(\'<iframe src="'.$tar[0].$src.'"'.$css.'scrolling="no" frameborder="0"></iframe>\');</script>';
    } else {
     $_mv .= ' <object type="text/html" data="'.$tar[0].$src.'"'.$css.'></object>';
    }
   } else {
    $_mv .= ' <object style="width:'.$w.'px; height:'.$h.'px;">'.($vendor=='sb' ? '' : '<param name="movie" value="'.$tar[0].$src.'"></param>')
         .'<embed src="'.$tar[0].$src.'" type="'.$tar[1].'" '.$tar[2].' width="'.$w.'" height="'.$h.'"></embed>
 </object>';
   }
   $_mv .= NL.'</div>';
   $com = str_replace($movlinks[0][$i], $_mv, $com);
  }
 }
 // アマゾンアソシエイト処理
 # Format
 # <!--AMAZON:asin--><a href="IMAGE.jpg" title="tag:tag">Item</a><!--/AMAZON:asin-->
 if(USE_AMAZON_ASSOCIATE){
  $com = preg_replace('{<!--AMAZON:(.+?)--><a href="(.+?)" title="(?:.+?):(.+?)">(.+?)</a><!--/AMAZON:\\1-->}e',
  "'<div class=\"amazon-box\">'.getAwsItem(\"$1\", \"$3\", \"$4\", \"$2\").'<hr class=\"clear\" /></div>`'",  $com);
 }

 if(ENABLE_NEW_WINDOW){
  $extlink = ' rel="external nofollow"';
  $linkimg = '<img class="extlink-icon" src="'.$theme_dir.'Images/external-link.png" width="12" height="12" alt="Link" title="外部リンク" /> ';
  $com = preg_replace('{<a href="([^"]+?)"(.*?)>(.+?)</a>}', '<a href="$1"'.$extlink.'$2>$3</a>'.$linkimg, $com);
 } else $extlink = $linkimg = '';
 $com = preg_replace('{'.V_URL.'}', '<a'.$extlink.' href="$1$2">$1$2</a>'.$linkimg, $com);
 
 // グーグル検索処理
 $com = preg_replace('{\[g\](.+?)\[\/g\]}ie',
        "'<a title=\"グーグルで検索\" href=\"#\" onclick=\"googleIt(\''.str_replace(\"'\",\"\'\",'$1').'\');return false;\" onkeypress=\"return(ture);\">$1</a><sup class=\"google-it\">G</sup>'", $com);
 // Wikipedia検索処理
 $com = preg_replace('{\[w\](.+?)\[/w\]}ie',
        "'<a title=\"Wikipediaで検索\" href=\"#\" onclick=\"wikipediaIt(\''.str_replace(\"'\",\"\'\",'$1').'\');return false;\" onkeypress=\"return(ture);\">$1</a><span class=\"google-it\">W</span>'", $com);
 // スター評価処理
 if(preg_match_all('{\[stars:(\d+?(\.5|))/(\d+?)\]}', $com, $star)){
  $len = sizeof($star[0]);
  for ($j = 0; $j < $len; $j++){
   $stars = '<span class="stars" title="'.$star[3][$j].' 点中 '.$star[1][$j].' 点">';
   for ($i=0; $i<floor($star[1][$j]); $i++) $stars .= '<img src="'.$theme_dir.'Images/star.png" alt="" />';
   $stars .= !empty($star[2][$j]) ? '<img src="'.$theme_dir.'Images/star-half.png" alt="" />' : '';
   for ($i=0; $i<(int)($star[3][$j]-$star[1][$j]); $i++) $stars .= '<img src="'.$theme_dir.'Images/star-null.png" alt="" />';
   $stars .= '</span>'.NL;
   $com = str_replace($star[0][$j], $stars, $com);
  }
 }
 if(HEADLINE_MODE && !$alone && !strpos($com, '<!--]]-->')){
  $com .= NL.'<p class="headline-readmore"><a '.( (AJAX_COMPAT && !$mht)?' onclick="loadPage(\''.substr($id,0,10).'\', 1, true);return false;"':'').' href="'.$pm_link.'">このエントリーの続きを読む≫</a></p>'.NL;
 }
 $com = my_parser($com, ENABLE_BR);
 if(isset($escaped)) $com = str_replace(array('[ESCAPED]', '[escape]', '[/escape]', '`'), array($escaped, '', '', NL), $com);
 if(USE_SMILEY) $com = convert_smilies($com); # スマイリー変換
 if(strpos($com, '<!--HIDE-->')){
  $com = preg_replace('{<!\-\-HIDE\-\->(.+?)(?:<!\-\-/HIDE\-\->|(<!\-\-END\-\->))}s', NL.'<div class="readmore-div"><span class="readmore" title="もっと読む" onclick=\'readMore(this);return false;\'>もっと読む&raquo;</span><div style="display:none">$1</div>'.NL.'$2</div>', $com);
 }
 $com .= tagsNav($_id);
 $dat = date('Ymd', $_id);
 $date = date('Y/m/d', $_id);// Japanese Y: &#24180; M: &#26376; d: &#26085;
 $modify = ( ( isOwnerLoggedIn() || (ADMIN && $author==$SESSION->owner()) ) && $mode != 'backup') ?
 '<ins><a href="admin.php?mode=edit&amp;UID='.$id.'" rel="edit"><img title=" この内容を修正 " src="'.$theme_dir.'Images/edit.png" alt="" /></a>&nbsp;
  <a href="admin.php?mode=del&amp;UID='.$id.'" onclick="return my_confirm(\'この記事を\')"><img title=" 削除します " src="'.$theme_dir.'Images/delete.png" alt="" /></a></ins>' : '';
 if($modify != ''){
  list($edit,) = explode('&nbsp;', $modify); $edit = '</a>&nbsp;&nbsp;'.str_replace(array('</a>', '<ins>'), '', $edit);
 } else $edit = '';
 if(COMMENT_AUTO_SUSPEND && COMMENT_APPEND_SPAN * 86400 < (time() - $_id)){ 
  $allowComment = 0;
 } else $allowComment = $cmtInfo[1];
 $toggle_comment = (($cmtInfo[0] || $tbInfo[0]) && ($UID==''||$ajax_list) && AJAX_COMPAT && !$mht) ? '<hr class="clear" /><div class="cute-button" onclick=\'loadComments('.$id.');\'><button title="ここでコメント・トラックバックを展開します">'.($cmtInfo[0]+$tbInfo[0]).'件のレスポンス [+]</button></div>' : '';

 if($allowComment && AJAX_COMPAT && $cmtInfo[0]==0 && $ajax_list){
  $comment_box = '<hr class="clear" />'.NL.
   '<div class="cute-button cute-reply" onclick="loadCommentForm('.$id.');"><button title="コメントフォームを表示">コメントする</button></div>';
 } else $comment_box = '';
 $draft_pre = $draft_mode ? '<div class="draft">'.($ontime ? '<strong>[オンタイム投稿記事]</strong>' : '') : '';
 $draft_post = $draft_mode  ? '</div><!--#draft-->' : '';
 
 if($cat_icon != ''){
  list($cat_icon, $w, $h) = explode('|', $cat_icon);
  $cat_icon = '<a href="'.(MODE_STATIC ? 'category/' : 'index.php?mode=category&amp;aim=').'%_ARTCL_CATEGORY_ASC_%'.$apres.'"><img src="'.$cat_icon.'" alt="icon" title="'.str_replace(',',' &raquo; ',$cat).'： クリックでこのカテゴリーの記事のみ表示します" width="'.$w.'" height="'.$h.'" /></a>';
 }
 $resInfo = $tbInfo[0] + $cmtInfo[0];
 $_ARTCL_BOX = preg_replace('{%_ARTCL_DATE_FORMAT\[(.+?)\]_%}e', "date('$1', '$_id')", $_ARTCL_BOX_FORMAT);
 $_ARTCL_BOX = preg_replace('{%_ARTCL_TIME_FORMAT\[(.+?)\]_%}e', "date('$1', '$_id')", $_ARTCL_BOX);
 
 if($resInfo){ // レスポンスあり
  $_ARTCL_BOX = preg_replace('{%_ARTCL_RESPONSE:(.+?):_%}', '$1', $_ARTCL_BOX);
 } else $_ARTCL_BOX = preg_replace('{\s?%_ARTCL_RESPONSE:.+?:_%\s}', '', $_ARTCL_BOX);
 if($cmtInfo[0] > 0){ // コメントあり
  $_ARTCL_BOX = preg_replace('{%_ARTCL_COMMENT:(.+?):_%}', '$1', $_ARTCL_BOX);
  if(!$allowComment || !$cmtInfo[1]){
   $_ARTCL_BOX = preg_replace('{ class="[^"]+?" title=".+?"}', ' class="comment-entree" title="コメントを読む"', $_ARTCL_BOX);
   $_ARTCL_BOX = str_replace('#comment', '#responses', $_ARTCL_BOX);
  }
 } else { // コメントなし
  $_ARTCL_BOX = preg_replace('{%_ARTCL_COMMENT:(.+?):_%}', $allowComment ? '$1' : '', $_ARTCL_BOX);
 }

 if($tbInfo[1]==0){
  $_ARTCL_BOX = preg_replace('{%_ARTCL_TRACKBACK:(.+?):_%}', '', $_ARTCL_BOX);
 } else $_ARTCL_BOX = preg_replace('{%_ARTCL_TRACKBACK:(.+?):_%}', '$1', $_ARTCL_BOX);
 
 /*if($mode != 'page' && strpos($_ARTCL_BOX_FORMAT, '%_ARTCL_SBM')){
  $sbm_num = socialBookmark($id, $title, $pm_link, ($ajax_list || !$alone) ? 0 : 1);
  if($alone){
   $_ARTCL_BOX = preg_replace('{%_ARTCL_SBM:.+?:_%}', $sbm_num, $_ARTCL_BOX);
  } else $_ARTCL_BOX = preg_replace('{%_ARTCL_SBM:(.+?):_%}', "<!--$title|$pm_link-->$1", $_ARTCL_BOX);
 }*/
 if($cat_icon==''){
  $_ARTCL_BOX = preg_replace('{<([a-z0-9]+?) .*?>%_ARTCL_CATEGORY_ICON_%</\\1>}', '', $_ARTCL_BOX);
 }
 if($cat == '%CAT%'){ $catlink = '';} else list($cat, $catlink) = trans_cat($cat, TRUE, TRUE);
 $_ARTCL_ARRAY = array(
  '<!--article-->' => $draft_pre,
  '%_ARTCL_ID_%' => $id,
  '%_ARTCL_PMLINK_%' => $pm_link,
  '%_ARTCL_TITLE_%' => $title.$reviews.$edit,
  '%_ARTCL_AUTHOR_%' => $author,
  '%_ARTCL_AUTHOR_ASC_%' => url_encode($author),
  '%_ARTCL_CATEGORY_%' => categoryNav($cat, $catlink),
  '%_ARTCL_CATEGORY2_%' => categoryNav($cat, $catlink, '', TRUE),
  '%_ARTCL_CATEGORY_ICON_%' => $cat_icon,
  '%_ARTCL_CATEGORY_ASC_%' => $catlink,
  //'%_ARTCL_TAGS_%' => tagsNav($id),
  '%_ARTCL_CONTENT_%' => NL.$com.$toggle_comment.$comment_box,
  '%_CMT_NUM_%' => $cmtInfo[0],
  '%_TB_NUM_%'=> $tbInfo[0],
  '%_RES_NUM_%'=> $resInfo,
  '%_ARTCL_MOD_%' => $modify,
  '</div><!--#article-->' => $draft_post.'</div><!--#article-->',
 );
 if($mode != 'page' && strpos($_ARTCL_BOX_FORMAT, '%_ARTCL_SBM_%')){
  $_ARTCL_ARRAY += array('%_ARTCL_SBM_%' => socialBookmark($id, $title, $pm_link, ($ajax_list || !$alone) ? 0 : 1));
 }
 if($alone) $_ARTCL_BOX  = str_replace('<div class="article-content"', '<div class="article-content shown-alone"', $_ARTCL_BOX);
 if($_ARTCL_BOX_UNITED==TRUE && !$alone){ // 同一日付の記事を連結する
  if($index===0){
   if($inf_same){
    $_ARTCL_BOX  = str_replace('<div class="article"', '<div class="article-united"><div class="article"', $_ARTCL_BOX);
    $_ARTCL_BOX = str_replace('</div><!--#article-->',
    '</div><!--#article-->'.NL.'<div class="separator" title="下の記事は同じ日のエントリーです">&nbsp;</div>', $_ARTCL_BOX);
   }
  }
  if($index==='LAST' || $index===($displayNumber - 1)){
   if($sup_same){
    $_ARTCL_BOX = preg_replace('{<(.+?) class="article-date">.+?</\\1>}s', '', $_ARTCL_BOX);
    $_ARTCL_BOX = str_replace('</div><!--#article-->', '</div><!--#article--></div><!--#united-->', $_ARTCL_BOX);
   }
  }
  if($index > 0 && $index < $displayNumber - 1){
   if($sup_same){
    $_ARTCL_BOX = preg_replace('{<(.+?) class="article-date">.+?</\\1>}s', '', $_ARTCL_BOX);
    if(!$inf_same){
     $_ARTCL_BOX = str_replace('</div><!--#article-->', '</div><!--#article--></div><!--#united-->', $_ARTCL_BOX);
    }
   }
   if($inf_same){
    $_ARTCL_BOX = str_replace('</div><!--#article-->',
    '</div><!--#article-->'.NL.'<div class="separator" title="下の記事は同じ日のエントリーです">&nbsp;</div>', $_ARTCL_BOX);
    if(!$sup_same){
     $_ARTCL_BOX  = str_replace('<div class="article"', '<div class="article-united"><div class="article"', $_ARTCL_BOX);
    }
   }
  }
 }
 return $RDF.str_replace(array_keys($_ARTCL_ARRAY), array_values($_ARTCL_ARRAY), $_ARTCL_BOX);
}

function convert_smilies($str){
 global $_SMILIES;
 return str_replace(array_keys($_SMILIES), array_values($_SMILIES), $str);
}

function show_archives(){ // mode==archives
 global $LOGS, $DIVISION, $displayMode;
 if(empty($LOGS[0])) $LOGS = array();
 $LOGY = array_values(array_unique(preg_replace('|^.+?(\d{4})\d{2}.*$|', '\\1', $LOGS)));
 $body = '<div class="archives-list">
 <h3>'.count($LOGS).'個のアーカイブがあります</h3>
 <ul>'.NL;
 foreach($LOGY as $Y){
  $body .= '<li><h4>'.$Y.'</h4><ul>'.NL;
  foreach($LOGS as $i=>$logs){
   $_logs[] = basename($logs);
   $_count = count( my_file($logs));
   $year = substr($_logs[$i], 0, 4); $month = substr($_logs[$i], 4, 2);
   if($Y == $year){
    $__logs = $year."年".$month."月 [".$_count."]";
    $body .= '  <li><a href="'.(MODE_STATIC ? $year.'/'.$month.'/'.$displayMode : 'index.php?date='.$year.$month).'">'.$__logs.'</a></li>'.NL;
   }
  }
  $body .= '</ul></li>'.NL;
 }
 $body .= '  </ul></div>'.NL;
 return $DIVISION['body'] = $body;
}

function show_category(){ // カテゴリーの一覧表示
 global $aim, $categories, $apres, $_cache, $displayMode, $CATEGORY_LIST, $DIVISION;
 if(!isset($CATEGORY_LIST)) include_once (OD.'category.ini.php');
 $no_entry = 'title="このカテゴリーの記事はまだないようです"';
 $yes_entry = 'title="クリックでこのカテゴリーの記事だけを表示します"';
 $link1 = MODE_STATIC ? 'category/' : 'index.php?mode=category&amp;aim=';
 if($aim != ''){
  $hit = preg_grep('{(\t'.$aim.')\|}', $CATEGORY_LIST);
  if(!empty($hit)){
   $hit = reset($hit); list($aim, $catlink) = explode("\t", $hit); list($catlink,) = explode('|', $catlink, 2);
  }
  if(strpos($aim, ',')){ # sub
   list($main, $sub) = explode(',', $aim, 2); list($mainlink, $sublink) = explode('/', $catlink);
   $aim = $main.','.$sub;
   $_aim = '<a href="'.$link1.$mainlink.$apres.'">'.$main.'</a> &raquo; '.$sub;
  } else {
   $_aim = '<a href="'.$link1.$catlink.$apres.'">'.$aim.'</a>';
  }
  $lines = get_articles_by_category($aim);
  $link2 = MODE_STATIC ? 'category/' : 'index.php?mode=category';
  if(isset($main)){ # 子カテ
   $DIVISION['header'] .= '
  <h3 class="category-nav center">
   [ <a href="'.$link2.'">カテゴリー</a> &raquo; '.$_aim.' ]
  </h3>
  ';
  } else { # 親
   $DIVISION['header'] .= '
  <h3 class="category-nav center">
   [ <a href="'.$link2.'">カテゴリー</a> &raquo; '.$_aim.' ]
  </h3>
   ';
  }
  if($displayMode == 'box'){
   return $DIVISION['body'] = HEADLINE_MODE ? show_headline($lines) : show_box_all($lines);
  } else return show_lists($lines);
 } else {
  $DIVISION['header'] .= '';
 }
 return $DIVISION['body'] = '<div class="category-list">
 <h3 class="center">'.count($CATEGORY_LIST).' 個のカテゴリーがあります</h3>
 <ul>'.NL.$categories.' </ul></div>'.NL;
}

function refresh_page($dest='index.php', $timer=1000, $standalone=FALSE){ // JavaScriptでのページ更新
 global $DIVISION;
 if(!isset($DIVISION['header'])) $DIVISION['header'] = '';
 $js = '<script type="text/javascript">/*<![CDATA[*/var _l=\''.$dest.'\'.replace(/&amp;/g,"&");setTimeout(\'self.location.replace("\'+_l+\'")\','.$timer.');/*]]>*/</script>';
 if($standalone) return $js.NL; else $DIVISION['header'] .= $js;
}

function page_back($timer=1000, $standalone=0){ // JavaScriptでのページ更新
 global $DIVISION;
 $back = '<script type="text/javascript">/*<![CDATA[*/setTimeout("history.back(-1);",'.$timer.');/*]]>*/</script>';
 if(isset($DIVISION['header'])){
  $DIVISION['header'] .= $back;
 }
 if($standalone) echo '<div class="cute-button" style="margin-left: 47%;"><button onclick="history.back(-1);"> 戻る </button></div>';
}

function cat_select($cat='', $option='', $action='', $name='category', $encode=FALSE){ // for select menu
 include (OD.'category.ini.php');
 $c = NL.'<select name="'.$name.'" id="'.$name.'"'.$action.'>'.NL;
 if($option != ''){ # option format is "value|name"
  list($value, $name) = explode('|', $option);
  $c .= ' <option value="'.$value.'"> '.$name.' </option>'.NL;
 }
 foreach ($CATEGORY_LIST as $line){
  list($_cat,) = explode('|', $line, 2); list($_cat, $catlink) = explode("\t", $_cat);
  $s = ($cat==$_cat || $cat==$catlink) ? 'selected="selected"' : '';
  $c .= ' <option value="'.($encode ? $catlink : $_cat).'" '.$s.'>'.str_replace(',', ' &raquo; ', $_cat).'　</option>'.NL;
 }
 $c .= '</select>'.NL;
 return $c;
}

function categoryNav($cat, $catlink, $separator='&raquo;', $short=FALSE){ # $cat format: category(,subcategory)
 global $apres;
 if(empty($apres)) $apres = MODE_STATIC ? '/' : '';
 if(MODE_STATIC){
  $base = $short ? '' : '<a href="category/">カテゴリー</a> '.$separator;
  $link = 'category/';
 } else {
  $base = $short ? '' : '<a href="index.php?mode=category">カテゴリー</a> '.$separator;
  $link = 'index.php?mode=category&amp;aim=';
 }
 if(strpos($cat, ',')){
  list($main, $sub) = explode(',', $cat); list($mainlink, $sublink) = explode('/', $catlink);
  return $base.' <a title="このカテゴリーを表示" href="'.$link.$mainlink.$apres.'"> '.$main.'</a> '.$separator.'
   <a title="このカテゴリーを表示" href="'.$link.$mainlink.'/'.$sublink.$apres.'"> '.$sub.'</a>';
 } else return $base.' <a title="このカテゴリーを表示" href="'.$link.$catlink.$apres.'"> '.$cat.'</a>';
}

function trans_cat($cat, $encode=TRUE, $pair=FALSE){ // from v1.7.7
 global $CATEGORY_LIST;
 include (OD.'category.ini.php');
 foreach ($CATEGORY_LIST as $item){
  $pat = $encode ? "\t$cat\t" : "\t$cat|";
  $mat = strstr("\t$item", $pat);
  if($mat != FALSE){
   if($encode){
    list($mat,) = explode('|', str_replace($pat, '', $mat), 2);
   } else list($mat,) = explode("\t", $item, 2);
   return $pair ? array($cat, $mat) : $mat;
  }
 }
}

function trans_page($target, $encode=TRUE){ // from v1.7.3
 global $PAGES_LIST;
 include (OD.'pages.ini.php');
 foreach ($PAGES_LIST as $list){
  list(,,$name, $link,) = explode('|', $list);
  if($target == $name || $target == $link) return $encode ? $link : $name;
 }
}

function my_file($logfile, $case=''){
 if(!is_file($logfile)) return array();
 $lines = file($logfile);
 if($case === -1) return array($lines, array_values(preg_grep('/^\d{9,}\|/', $lines))); # both array
 return $case ? $lines : array_values(preg_grep('/^\d{9,}\|/', $lines)); # real / nominal
}

function get_articles_by_date($date){ // yyyymmdd形式の日付に一致する記事を配列で返す
 $LINES = my_file(LOG.substr($date,0,6).EXT);
 $hits = array();
 foreach ($LINES as $line){
  list($id,) = explode('|', $line);
  if(date('Ymd', substr($id,0,10))==$date){
   $hits[] = $line;
  }
 }
 unset($LINES);
 return $hits;
}
function get_articles_by_category($cat, $start=0, $length=100000, $rsort=FALSE){ // 指定したカテゴリの記事を配列で返す
 $LOGS = my_glob(EXT, 'log/');
 $LINES = array();
 $count = 0;
 for($j = 0, $l = count($LOGS); $j < $l; $j++){
  if(empty($LOGS[$j]) || !is_file($LOGS[$j])) continue;
  if($fp = @fopen($LOGS[$j], "rb")){
   while(!feof($fp)){
    $line = fgets($fp);
    if($line && substr($line, -2) != '|'.NL) $line .= fgets($fp);
    if($line == '') continue;
    list(,$category,) = explode('|', $line, 3);
    if($cat==$category || (SEE_CAT_HIERARCHY ? 0 : strstr($category, "$cat,"))){
     if(!empty($line) && $count++ >= $start){
      $LINES[] = rtrim($line).NL;
     }
     if(($count - $start) >= $length) break 2; // level 2!
    }
   } # while-loop
   fclose($fp);
  } # $fp
 } # for-loop
 if((defined('ADMIN') && !ADMIN) || !defined('ADMIN')) $LINES = preg_grep("{^\d{9,}\|}", $LINES);
 if($rsort) return array_reverse($LINES);
 return $LINES;
}
function get_articles_by_author($author, $start=0, $length=0){ // 指定したユーザーの記事を配列で返す
 global $LOGS;
 $LINES = array();
 $count = 0;
 for($j = 0, $l = count($LOGS); $j < $l; $j++){
  if($fp = @fopen($LOGS[$j], "rb")){
   while(!feof($fp)){
    $line = fgets($fp);
    if($line && substr($line, -2) != '|'.NL) $line .= fgets($fp);
    if($line=='') continue;
    list(,,,,$poster,) = explode('|', $line, 6);
    if($author==$poster){
     if(!empty($line) && $count++ >= $start){
      $LINES[] = rtrim($line).NL;
     }
     if(($count - $start) >= $length) break 2; // level 2!
    }
   } # while-loop
   fclose($fp);
  } # $fp
 } # for-loop
 return $LINES;
}

# 全ての記事を配列で返す. $maxが指定されたらその数まで
function get_all_articles($max='', $rsort=FALSE){
 global $LOGS;
 $LINES = array();
 $LOGSIZE = $cacheFileCount = 0;
 foreach ($LOGS as $i=>$log){
  if(is_file($log)) $LOGSIZE += @filesize($log);
  if($LOGSIZE > 1024 * 1024){ # 1MB超えたら
   if($rsort) $LINES = array_reverse($LINES);
   rewrite(DB.'tempLINES'.(++$cacheFileCount), $LINES);
   unset($LINES);
   $LINES = array();
  }
  $LINES = array_merge($LINES, my_file($log));
  if($max!=''){
   if(count($LINES) > $max) break;
  }
 }
 if($rsort) return array_reverse($LINES);
 return $LINES;
}

function get_sliced_articles($start=0, $length=10000, $sort='descend'){ // ある区間の記事のみ抽出
 global $LOGS;
 $LINES = array();
 $count = 0;
 if($sort!='descend' && is_array($LOGS)) $LOGS = array_reverse($LOGS);
 for($j = 0, $l = count($LOGS); $j < $l; $j++){
  if(!is_file($LOGS[$j])) continue;
  if($sort!='descend'){
   $BUF = DB."reversed.txt";
   rewrite($BUF, array_reverse(file($LOGS[$j])));
   $LOGS[$j] = $BUF;
  }
  if($fp = @fopen($LOGS[$j], "rb")){
   while(!feof($fp)){
    $line = fgets($fp);
    if($line && substr($line, -2) != '|'.NL) $line .= fgets($fp);
    if(!isOwnerLoggedIn() && substr($line, 10, 1)=='d') continue;
    if(!empty($line) && $count++ >= $start){
     $LINES[] = rtrim($line).NL;
    }
    if( ($count - $start) >= $length) break 2; // level 2!
   } # while-loop
   fclose($fp);
  } # $fp
 } # for-loop
 return $LINES;
}

function autolink($link){
 global $theme_dir;
 $extlink = (ENABLE_NEW_WINDOW) ? ' rel="external nofollow"' : '';
 $linkimg = ENABLE_NEW_WINDOW ? '<img class="extlink-icon" src="'.$theme_dir.'Images/external-link.png" width="12" height="12" alt="Link" title="外部リンク" /> ': '';
 $rep = array(
  '{\[\[(.+?):http://(.+?)\]\]}i' => "<a href=\"http://$2\"$extlink>$1</a>$linkimg",
  '{'.V_URL.'}' => "<a href=\"$1$2\"$extlink>$1$2</a>$linkimg"
 );
 return preg_replace(array_keys($rep), array_values($rep), $link);
}

function SORT_BY_DATE($a, $b){
 if($a == $b) return 0;
 return ($a > $b) ? -1 : 1;
}

function mk_fl($name){ // ファイル自動生成
 if(!is_file($name)){
  rewrite($name, '');
 }
}

function rewrite($file='', $data='', $add=FALSE){ // fopen()してデータ$dataを書き込む
 global $DIVISION;
 if(gettype($file) == 'string' && $file != '' && !is_file($file)){
  $ini = umask(0);
  $fp = @fopen($file, 'wb');
  @chmod($file, 0606);
  @fclose($fp);
  umask($ini);
 }
 $fp = fopen($file, "ab+");
 if(!$fp) rewrite($file, '');
 if($fp){
  if(flock($fp, LOCK_EX)){
   if(!$add) ftruncate($fp, 0);
   if(is_array($data)){
    foreach($data as $value){
     fputs($fp, rtrim($value).NL);
    }
   } else fputs($fp, $data);
   flock($fp, LOCK_UN);
  }
  fclose($fp);
 }
 return TRUE;
}

function rewrite_ini($file, $data='', $var=''){ // *.ini.php 用の書き込み関数
 global $DIVISION;
 $new_lines = array();
 if($var==''){
  $lines = file($file);
  $new_lines[] = rtrim(array_shift($lines));
  if(!strstr($new_lines[0], '<?php $')) return;
 } else {
  $new_lines[] = '<?php '.$var.' = array(';
  if(is_array($data)){
   foreach ($data as $dat) $new_lines[] = "'".rtrim($dat)."',";
  }
  $new_lines[] = ');?>';
  rewrite($file, $new_lines);
  return TRUE;
 }
 $end = rtrim(array_pop($lines));
 if(trim($end) != ');?>') $end = ');?>';
 if(is_array($data)){
  foreach ($data as $dat) $new_lines[] = "'".rtrim($dat)."',";
 }
 $new_lines[] = $end;
 rewrite($file, $new_lines);
}

/* Glob function */
function my_glob($needle, $dir, $saved=FALSE, $cache=''){
 if(!defined('DB')) include_once('owner/ini.inc.php');
 if($saved && is_file(PATH.DB.$cache)){
  return explode(NL, rtrim(get_file_content(PATH.DB.$cache)));
 }
 $LINES = array();
 if(!is_dir($dir)){
  $dir = PATH.$dir;
 }
 $d = opendir ($dir);
 while ($file = readdir ($d)) {
  if(strpos(' '.$file, $needle)){
   $LINES[] = $dir.$file;
  }
 }
 closedir ($d);
 usort($LINES, 'SORT_BY_DATE');
 return $LINES;
}

function get_file_content($file, $timeout=6){
 if(PHP_VERSION >= '4.3.0'){
  if(PHP_VERSION > 5){
   $ct = stream_context_create(array('http' => array('timeout' => $timeout)));
   $get = @file_get_contents($file, FALSE, $ct) or '';
  } else {
   @ini_set('default_socket_timeout', $timeout);
   $get = file_get_contents($file);
  }
 } else $get = implode('', file($file));
 if(!$get) return ''; else return $get;
}

function checkHoliday($date){ // 休日チェック
 global $hd;
 if(empty($hd)) return 0;
 return isset($hd->holidays[$date]) ? 1 : 0;
}

function _header($to){
 header("Location: ".str_replace("\\/", "/", $to));
 exit;
}

function P($s, $exit=FALSE, $adminOnly=FALSE){ //Debug
 if($adminOnly && !defined('ADMIN')) return;
 ob_start();
 echo 'Debug:<pre style="margin-top:20px;min-height:30px;position:relative;">';
 print_r($s);
 echo '</pre>'.NL;
 register_shutdown_function('ob_end_flush');
 if($exit) exit;
}

function get_cmt_array($uid, $countOnly=FALSE){
 $cmts = array();
 $d = opendir (CMT_DIR);
 while ($file = readdir ($d)) {
  if(strstr($file, $uid)){
   $cmts = file(CMT_DIR.$file);
   break;
  }
 }
 closedir ($d);
 if($countOnly){
  if(empty($cmts)) return 0;
  $parts = explode('|', $cmts[0]);
  unset($cmts);
  return isOwnerLoggedIn() ? $parts[3] : (int)($parts[3] - $parts[4]);
 } else return $cmts;
}

function get_tb_count($uid){ // 2004/06/06 revised
 $tb_DB = DB.'trackback.db';
 if(is_file($tb_DB)){
  $tb_content = get_file_content($tb_DB);
  if(!empty($tb_content)){
   $tb_db_data = unserialize($tb_content);
   if(array_key_exists("$uid", $tb_db_data))return $tb_db_data[$uid];
   else return '0';
  }
 }
 $file = TB_DIR.$uid.EXT;
 if(is_file($file)){
  if(@filesize($file) > 0 ){
   return count( unserialize( get_file_content($file) ) );
  } else return '0';
 } else return '0';
}

function slice_file_by_size($src='', $dest='', $size = "1024 * 1024"){ // ファイルを指定したサイズで分割
 $fp = fopen($src, 'rb');
 $output = fread($fp, $size);
 fclose($fp);
 rewrite($dest, $output);
}

function checkADMIN($strict=FALSE, $msg = ''){
 $msg = !$msg ? 'Oops!' : $msg;
 if(!defined('ADMIN')) die($msg);
 if($strict==TRUE){
  if(defined('ADMIN') && ADMIN===FALSE) die($msg);
 }
}

function my_substr($string, $start=0, $length=0){   //Revised in ver1.7.1
 global $mb;
 if($mb){
  $string = (mb_strlen($string, ENCODE) > $length) ? mb_substr($string, $start, $length, ENCODE)."..." : $string;
 } else {
  $_len = $length*2;
  $string = (strlen($string)>$_len) ? substr($string, $start, ($_len - strlen($string)%2))."..." : $string;
 }
 return $string;
}

function put_RDF($uid, $title, $category, $body, $author, $simple=TRUE){
 global $_self;
 $rep = array('"'=>'\"','`'=>'','--'=>'__');
 if(strpos($title, ',')){
  list($title, $pm_title) = explode(',', $title);
  $pm_link = MODE_STATIC ? (WITH_DATE ? date('Ym-', substr($uid, 0, 10)) : '').$pm_title.EXT_STATIC : 'index.php?UID='.$uid;
 } else $pm_link = MODE_STATIC ? $uid.EXT_STATIC : $_self.'?UID='.$uid;
 if(!$simple){
  $body = preg_replace('{\[g\]([^\/]+?)\[/g\]}', '$1', trim(strip_tags($body)));
  $body = my_substr(str_replace(array_keys($rep),array_values($rep),$body),0,100);
 }
 return '
<!--
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
         xmlns:dc="http://purl.org/dc/elements/1.1/"
         xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
<rdf:Description
    rdf:about="'.ROOT_PATH.$_self.'?UID='.$uid.'"
    trackback:ping="'.ROOT_PATH.'trackback.php?UID='.$uid.'"
    dc:identifier="'.ROOT_PATH.$_self.'?UID='.$uid.'"
    dc:title="'.str_replace(array_keys($rep),array_values($rep),$title).'"'.($simple ? ' />' :
'
    dc:subject="'.str_replace(array_keys($rep),array_values($rep),$category).'"
    dc:description="'.$body.'"
    dc:creator="'.$author.'"
    dc:date="'.date('D, d M Y H:i:s+09:00', $uid).'" />
').'
</rdf:RDF>
-->
';
}

function get_http($url='', $header = FALSE){
 $_url = parse_url($url);
 $_url['query'] = isset($_url['query']) ? '?'.$_url['query'] : '';
 $_url['port'] = isset($_url['port']) ? $_url['port'] : 80;
 $request  = "GET ".$_url['path'].$_url['query']." HTTP/1.0\r\n";
 $request .= "Host: ".$_url['host']."\r\n";
 $request .= "User-Agent: PPBLOG v".PPBLOG_VERSION."\r\n\r\n";
 error_reporting(0);
 if($fp = @fsockopen($_url['host'], $_url['port'], $errno, $errstr, $timeout=5)){
  $reply = '';
  fputs($fp, $request);
  do {
   $reply .= fgets ($fp, 4096);
  } while (strpos($reply, "\r\n\r\n")===FALSE);
  $reply = $header ? $reply : '';
  while (!feof($fp)) $reply .= fgets ($fp, 4096);
  fclose($fp);
  return $reply;
 } else return FALSE;
}

function getAwsItem($ASIN='', $asTag='ppblog-22', $item='', $url='', $AWSKEY='AKIAIAAAF5TNOKUT32PA'){
 global $theme_dir, $amazonAPIResponse;
 $cache = my_glob('aws_'.$ASIN.'_', DB);
 if(!empty($cache)){
  list(,,$utime) = explode('_', $cache[0]);
  if(date('Ymd') - date('Ymd', $utime) > 0){
   unlink(PATH.$cache[0]);
  } else return get_file_content($cache[0]);
 }
 $amazonAPIResponse = TRUE;
 include_once 'amazon_associate.php';

 $response = $amazonAPIResponse;
 $noImg = ROOT_PATH.'Images/notfound-amazon.png';
 $stars_url = ROOT_PATH.$theme_dir.'Images/';

 $rating = array(
  '0.0' => 'stars0-0.png',  '0.5' => 'stars0-5.png',  '1.0' => 'stars1-0.png',  '1.5' => 'stars1-5.png',
  '2.0' => 'stars2-0.png',  '2.5' => 'stars2-5.png',  '3.0' => 'stars3-0.png',  '3.5' => 'stars3-5.png',
  '4.0' => 'stars4-0.png',  '4.5' => 'stars4-5.png',  '5.0' => 'stars5-0.png',
 );
 $res = str_replace('</Request>', "</Request>\n", $response);
 $r = explode(NL, $res); $info = '';
 if($response != FALSE && isset($r[1])){
  if(preg_match('{<Item>(.+?)</Item>}', $r[1], $_item)){
   $itemInfo = array();

   foreach ($INFO as $key=>$val){
    $_key = strpos($key, 'Price') ? substr($key, 0, 10) : substr($key, 0, 5);
    if(strpos($_item[1], $_key)===FALSE) continue;
    $itemInfo[$val] =  preg_replace("{^.*?".$key.".*$}i", "$1", $_item[1]);
   }
   if(isset($itemInfo['url'])){
    $img = '<img src="'.$itemInfo['url'].'" width="'.$itemInfo['w'].'" height="'.$itemInfo['h'].'" alt="item" title="アマゾンで詳しく"/>'.NL;
   } else $img = '<img src="'.$noImg.'" width="85" height="79" alt="" />'.NL;
   if(isset($itemInfo['reviews'])){
    if(preg_match_all('{<Review>(.+?)</Review>}', $itemInfo['reviews'], $_reviews)){
     $rev = '<dl style="display: none;">';
     foreach($_reviews[1] as $review){
      $rev .= preg_replace('{.*?<ASIN>.+?</ASIN><Rating>(.+?)</Rating>.+?<Reviewer><CustomerId>(.+?)</CustomerId>.*?<Name>(.+?)</Name>.*?</Reviewer>.+?<Date>(.+?)</Date><Summary>(.+?)</Summary>.*$}', "<dt>$4 <a href=\"http://www.amazon.co.jp/gp/pdp/profile/$2/ref=cm_cr_auth\">$3</a></dt><dd><img src=\"${stars_url}stars$1-0.png\" width=\"51\" height=\"11\" alt=\"rating:$1/5\"/>$5</dd>".NL, $review);
     }
     $rev .= NL.'   </dl>'.NL.'   ';
    }
   }
   if(isset($itemInfo['genre'])){
    $genre = $itemInfo['genre'];
   } elseif(isset($itemInfo['ProductTypeName'])){
    $genre = $itemInfo['ProductTypeName'];
   } else $genre = '';
   $info .= '
   <p class="entry"><a href="'.$url.'">'.$img.'</a></p>
   <p class="title"><a href="'.$url.'">'.$item.'</a></p>
   <ul class="amazon-info">
    '.(isset($itemInfo['artist'])? '   <li>アーティスト： <span>'.$itemInfo['artist'].'</span></li>' : '').'
    <li> メーカー・販売： <span>'.(isset($itemInfo['label']) ? $itemInfo['label'] : $itemInfo['man']).'</span></li>
    <li> アマゾン価格： <span>'.(isset($itemInfo['price']) ? $itemInfo['price'] : ' &mdash; ').'</span></li>
    '.(isset($itemInfo['ranking']) ? '<li> 売り上げランキング： <span>'.number_format($itemInfo['ranking']).'位</span></li>' : '').'
    '.(isset($itemInfo['date']) ? '<li> リリース： <span>'.$itemInfo['date'].'</span></li>' : '').'
    '.($genre ? '<li> ジャンル・カテゴリー：  <span>'.$genre.'</span></li>' : '')
     .(isset($itemInfo['rate']) ?
     '<li class="review"> レビュー評 価：<img src="'.$stars_url.$rating[$itemInfo['rate']].'" width="51" height="11" alt="" title="アマゾンレビューでの平均評価：5点中'.$itemInfo['rate'].'点 " style="vertical-align: middle;"/>
      <a href="#" title="レビュー抜粋（'.date('Y-m-d').' 時点）"
      onclick=\'o(this.nextSibling).toggle();return false;\'>[詳 細]</a>'.$rev.'</li>' : '').'
   </ul>
   ';
  }#preg_match
  if(empty($cache) && $info != '') rewrite(DB.'aws_'.$ASIN.'_'.time(), $info); // Create cache
 } else { # Retrieve failed
  $info .= '
   <p class="entry"><a href="'.$url.'"><img src="'.$noImg.'" width="85" height="79" alt="" /></a></p>
   <p class="title"><a href="'.$url.'">'.$item.'</a></p>
   <ul class="amazon-info">
    <li><span class="alert">情報取得失敗</span></li>
   </ul>
  ';
 }
 return $info;
}

function theme_selector(){ // Revised from ver.1.6.5
 global $theme, $THEME_LIST;
 include_once (OD.'theme.ini.php');  # get $THEME_LIST
 $s = '
  <ul>'.NL;
 foreach($THEME_LIST as $_theme=>$path){
  $cur = ($path==$theme) ? ' class="current"' : '';
  if($cur==''){
   $s .= '   <li><a href="index.php?theme='.$path.'">'.$_theme.'</a></li>'.NL;
  } else $s .= '   <li'.$cur.'>'.$_theme.'</li>'.NL;
 }
 $s .= '  </ul>'.NL;
 return $s;
}

function test_ip($ip='', $array=FALSE, $ini='owner/ban.ini.php'){ # 戻り値 1: blacklist, 404: denial, -1: allow posting
 global $BAN_LIST, $NC_LIST;
 if($ip=='') return;
 if(strpos($ini,'ban')){
  include_once($ini);
  $LIST = $BAN_LIST;
 } else {
  include_once(OD.'notcount.ini.php');
  $LIST = $NC_LIST;
 }
 $ips = explode('.', $ip);
 foreach ($LIST as $i=>$ban_ip){
  list(, $ban_ip, $NotFound) = explode('|', $ban_ip);
  $bi = explode('.', $ban_ip);
  if($ips[0]==$bi[0] && $ips[1]==$bi[1] && $ips[2]==$bi[2]){
   if($bi[3]=='*' || ($bi[3]==$ips[3])){
    if($array) return array(1, $i);
    return $NotFound ? 404 : -1;
   }
   if($bi[3]!='*' && $ips[3]=='*'){ #override
    if($array) return array(-1, $i);
    return $NotFound ? 404 : -1;
   }
  }
 }
 if($array) return array(0, -1);
 return -1;
}

function url_encode($data){
 if($data == '') return '';
 if(strpos($data, ',') > 0){
  $_data = array();
  foreach(explode(',', $data) as $dat) $_data[] = url_encode($dat);
  return implode('/', $_data);
 }
 if(preg_match('{^[a-z0-9#\+\s\|,_-]+$}i', $data)) return preg_replace('{\s}', '&ndash;', $data);
 return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($data)).'-E';
}

function url_decode($data){
 if(substr($data, -2) == '-E'){
  return base64_decode(str_replace(array('_', '-'), array('/', '+'), substr($data, 0, -2)));
 } else return str_replace('&ndash;', ' ', $data);
 
}

function my_encrypt($data, $key=OPASS){
 $key = md5($key);
 $keylen = strlen($key); // Thanks, Saru-san
 for($i = 0; $i < strlen($data); $i++){
  $data[$i] = $data[$i]^$key[$i%$keylen]; 
 }
 $data = str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($data));
 return $data;
}
function my_decrypt($data, $key=OPASS){
 $data = base64_decode(str_replace(array('_', '-'), array('/', '+'), $data));
 $key = md5($key);
 $keylen = strlen($key);
 for($i = 0; $i < strlen($data); $i++){
  $data[$i] = $data[$i]^$key[$i%$keylen];
 }
 return $data;
}

function tagsNav($id=''){
 global $apres, $TAGS_LIST;
 if(empty($apres)) $apres = MODE_STATIC ? '/' : ''; # Thanks, naoK!
 $tags = '';
 if(!isset($TAGS_LIST)) include_once (OD.'tags.ini.php');
 if(!empty($TAGS_LIST)){
  $hits = preg_grep("/$id/", $TAGS_LIST);
  $hits = array_values($hits);
  if(!empty($hits)){
   $tags .= '<p class="tags-entry" title="この記事のタグ">';
   foreach ($hits as $tag){
    list($t,) = explode('|', $tag);
    $link = 'http://technorati.com/tag/'.urlencode($t);
    $tags .= ('<a href="'.(MODE_STATIC ? 'tags/' : 'index.php?mode=tags&amp;aim=').urlencode(urlencode($t)).$apres.'" rel="tag" title="このタグのエントリーのみを表示">'.$t.'</a> &nbsp; ');
   }
   $tags .= '</p>'.NL;
  }
 }
 return $tags;
}

$SBM_LIST = array( # Nested array: (icon,width,height, register url, counter API, counter url)
  'はてなブックマーク' => array('hatenab.png,16,12', 'b.hatena.ne.jp/add?mode=confirm&amp;url=', 'api.b.st-hatena.com/entry.count?url=', 'b.hatena.ne.jp/entry/', 'sbm-hatena'),
  'del.icio.us' => array('deliciousb.png,14,14,', 'del.icio.us/post?url=', 'badges.del.icio.us/feeds/json/url/blogbadge?hash=', 'del.icio.us/url/', 'sbm-delicious'),
  'livedoorクリップ' => array('livedoorb.png,14,14', 'clip.livedoor.com/redirect?link=', 'api.clip.livedoor.com/json/comments?link=', 'clip.livedoor.com/page/', 'sbm-livedoor'),
  'Twitter' => array('twitter.png,14,14', 'twitter.com/home?status=Reading:', '', '', 'sbm-twitter'),
  'facebook' => array('facebook.png,14,14', 'www.facebook.com/share.php?u=', '', '', 'sbm-facebook'),
  'Buzzurl' => array('buzzurlb.png,14,14', 'buzzurl.jp/config/add/confirm?url=', 'api.buzzurl.jp/api/counter/v1/json?url=', 'buzzurl.jp/entry/', 'sbm-buzzurl'),
  'Yahoo!ブックマーク' => array('yahoob.png,16,16', 'bookmarks.yahoo.co.jp/action/bookmark?u=', 'num.bookmarks.yahoo.co.jp/yjnostb.php?urls=', 'bookmarks.yahoo.co.jp/url?url=', 'sbm-yahoo'),
  'グーグル ブックマーク' => array('googleb.png,14,14', 'google.com/bookmarks/mark?op=add&amp;bkmk=', '', '', 'sbm-google'),
);

$SBM_closeButton = is_file($SBM_closeButton = ($theme_dir.'Images/button-close.png')) ? $SBM_closeButton : 'Images/button-close.png';
$SBM_entryButton = is_file($SBM_entryButton = ($theme_dir.'Images/sbm.png')) ? $SBM_entryButton : 'Images/sbm.png';

function socialBookmark($uid='', $title='', $permlink='', $alone = TRUE, $via_ajax = FALSE, $count=0){
 global $mode, $SBM_closeButton, $SBM_entryButton, $SBM_LIST;
 $now = time(); $new_entry = FALSE; $sbm_file = DB.'social_bookmarks';
 if((strpos(ROOT_PATH, '27.0.0.1') && $alone) || strpos($uid, 'd')) return '';
 if(!is_file($sbm_file)) rewrite($sbm_file);
 $SOCIAL_BOOKMARKS = file($sbm_file);
 if(!empty($SOCIAL_BOOKMARKS)){
  $target = preg_grep('/{"UID":"'.$uid.'",/', $SOCIAL_BOOKMARKS);
  if(!empty($target)){
   $index = array_keys($target); $index = $index[0];
   $target = reset($target);
  } else {
   $new_entry = TRUE;
  }
 } else $new_entry = TRUE;

 $_title = rawurlencode($title);
 if($mode == 'write' || $mode == 'edit'){
  $s = '';
  foreach ($SBM_LIST as $list=>$a){
   list($src, $w, $h) = explode(',', $a[0]);
   $s .= '<img src="Images/bookmarks/'.$src.'" width="'.$w.'" height="'.$h.'" />';
  }
  return $s;
 }
 $s = NL; $total_count = 0;
 $json = '{"UID":"'.$uid.'","timestamp":"'.$now.'","bookmarks":{';
 $timestamp = isset($index) ? substr($target, 33, 10) : $now;
 $renewal = (!$new_entry && !$via_ajax && ($now - $timestamp > 3600 * 12 * 1)) ? TRUE : FALSE;
 if(MODE_STATIC){
  $_permlink = strstr($permlink, $uid) ? ROOT_PATH.'index.php?UID='.$permlink : ROOT_PATH.$permlink;
 } else $_permlink = ROOT_PATH.'index.php?UID='.$uid;
 foreach ($SBM_LIST as $list=>$a){
  list($src, $w, $h) = explode(',', $a[0]); $count = 0;
  //$count = $a[2] == '' ? 0 : '';
  if(strpos($a[0], 'ciou')){
   $url = 'http://'.$a[2].md5($_permlink);
  } else $url = 'http://'.$a[2].urlencode($_permlink);
  if($alone && ($new_entry || $renewal)){
   error_reporting(0);
   if(strpos($a[0], 'atena')){ // Hatena
    $count = @get_file_content($url) or 0;
    if($count != '(null)' && preg_match('|"count":"(\d+)",|', $count, $m)){
     $count = $m[1];
    }
   }
   if(strpos($a[0], 'ahoo')){ // Yahoo
    $count = @get_file_content($url) or 0;
    if($count != '' && preg_match('| ct="(\d+)"|', $count, $m)){
     $count = $m[1];
    }
   }
   if(strpos($a[0], 'ived')){ // livedoor
    $count = @get_file_content($url) or 0;
    if($count != '' && preg_match('|"total_clip_count":(\d+),|', $count, $m)){
     $count = $m[1];
    }
   }
   if(strpos($a[0], 'ciou')){ // delicious
    $count = @get_file_content($url) or 0;
    if($count != '' && preg_match('|"total_posts":"?(\d+)"?|', $count, $m)){
     $count = $m[1];
    }
   }
   if(strpos($a[0], 'uzzu')){ // Buzzul
    $count = @get_file_content($url) or 0;
    if($count != '' && preg_match('|"users":(\d+),|', $count, $m)){
     $count = $m[1];
    }
   }
   if(!is_numeric($count) || trim($count)=='') $count = 0;
   $total_count += $count;
  } else {
   if(!empty($target)){
    foreach (explode(',', $target) as $bookmark){
     if($pos = strpos($bookmark, ($bm=substr($a[4], 4)))){
      $count = str_replace(array('"','}'), '', substr($bookmark, $pos + strlen($bm) + 2));
      $total_count += $count;
     }
    }
   }
  } # !alone
  $counter = $count == 0 ? '' :
   '<a href="http://'.$a[3].(strpos($a[0], 'ciou') ? md5($_permlink) : $_permlink).'" rel="nofollow"><span class="'.$a[4].'" title="'.$list.'でのブックマーク数">'.$count.'</span></a>'.NL;
  $add = $a[1].$_permlink.'&amp;'.((strpos($a[0], 'ahoo') || strpos($a[0], 'acebo')) ? 't' : 'title').'='.$_title;
  if(strpos($a[0], 'witter')) $add = $a[1].$_title.'@'.$_permlink;
  $s .= '<a rel="nofollow" href="http://'.$add.'"><img src="Images/bookmarks/'.$src.'" title="この記事を'.$list.'に追加" width="'.$w.'" height="'.$h.'" alt="'.$list.'"/>'.($via_ajax ? ' '.$list : '').'</a>'.($counter=='' ? NL : ' ').$counter;
  if(strpos($a[0], 'ogle')) continue;
  // create JSON
  $json .= '"'.str_replace('sbm-', '', $a[4]).'":'.($count == '' ? 0 : $count).',';
 }
 $json = substr($json, 0, -1).'},"total":'.$total_count.'},'.NL; // delete last `,`
 if(!$via_ajax && $alone){
  if($renewal == TRUE){
   array_splice($SOCIAL_BOOKMARKS, $index, 1, $json);
   rewrite(DB.'social_bookmarks', $SOCIAL_BOOKMARKS);
  } elseif($new_entry){ // new entry
   array_unshift($SOCIAL_BOOKMARKS, $json);
   rewrite(DB.'social_bookmarks', $SOCIAL_BOOKMARKS);
  }
 }
 if($alone){
  return NL.' <ul class="solo">'.preg_replace(array('{<a rel="nofollow"}', '{</a>'.NL.'}'), array('  <li><a rel="nofollow"', '</a></li>'.NL), $s)
  .($total_count ? ' <li><span title="Total count:'.$total_count.'">T: '.$total_count.'</span></li>' : '').'</ul>';
  //return $total_count ? $s.' <span title="Total count:'.$total_count.'">T: '.$total_count.'</span>' : $s;
 } else if($via_ajax){
  //$s = '<ul class="sbm-box" id="SBM'.$uid.'">'.preg_replace(array('{<a rel="nofollow"}', '{</a>'.NL.'}'), array('<li><a rel="nofollow"', '</a></li>'.NL), $s).'</ul>';
  //return $total_count ? $s.'<p class="info">'.$total_count.'人のユーザーがブックマークしてます。</p>' : $s;
  $s = '<div class="sbm-box" id="SBM'.$uid.'">
  <p class="sbm-close"><img style="cursor: pointer;" src="'.$SBM_closeButton.'" alt="close" title="閉じる" onclick="this.parentNode.parentNode.style.display=\'none\';" /></p>
  <ul>'.preg_replace(array('{<a rel="nofollow"}', '{</a>'.NL.'}'), array('<li><a rel="nofollow"', '</a></li>'.NL), $s).'</ul>';
  return $total_count ? $s.'<p class="info">'.$total_count.'人のユーザーがブックマークしてます。</p></div>' : $s.'</div>';
 } else {
  //return array(($total_count ? $total_count : 0), "SBM:$total_count\t$uid\t$title\t$permlink");
  return '<img src="'.$SBM_entryButton.'" class="sbm-entry" title="ソーシャルブックマークへの登録をします" alt="SBM:'.$total_count."\t".$uid."\t".$title."\t".$permlink.'" /><span class="sbm-count">'.($total_count ? $total_count : ' -').'</span>';
 }
}

function showRanking($limit = RECENT_ENTRIES){
 global $RANKING;
 if(is_file(($ranking = OD.'ranking.ini.php'))){
  include $ranking;
  if(!empty($RANKING)){
   $h = NL; $class = '';
   foreach ($RANKING as $i => $r){
    if($i >= $limit) break;
    list($count, $uid, $pmlink, $title) = explode("\t", $r, 4);
    switch($i){
     case 0 : $class = ' class="rank-1st"'; break;
     case 1 : $class = ' class="rank-2nd"'; break;
     case 2 : $class = ' class="rank-3rd"'; break;
     default : $class = '';
    }
    $h .= '    <li'.$class.'><a href="'.ROOT_PATH.$pmlink.'" title="'.date('Y年n月j日の投稿', $uid).'">'.$title.'</a> <span title="閲覧数">'.$count.'</span></li>'.NL;
   }
   return $h;
  }
 }
}

function Auth($sid=''){ # Revised in ver 1.7.5
 global $SESSION;
 $SESSION = new Session($sid);
 return empty($SESSION->data) ? FALSE : TRUE;
}

function BenchMark($order=4){
 static $init = 0;
 list($usec, $sec) = explode(" ", microtime());
 $fin = (float)$usec + (float)$sec;
 return ($init==0) ? ($init=$fin) : sprintf("%.${order}f", ($fin-$init));
}

?>
